AzureIntermediate

Azure Serverless Architecture: Functions, Logic Apps, and Event Grid

9 min read

TL;DR

Master Azure serverless computing with this comprehensive guide covering Azure Functions, Logic Apps, and Event Grid. Learn implementation patterns, best practices, and real-world scenarios.

Azure Serverless Architecture: Functions, Logic Apps, and Event Grid

Executive Summary

Azure's serverless tier is three services with distinct jobs: Functions runs your code in response to events, Logic Apps orchestrates workflows and SaaS integrations visually, and Event Grid routes events between producers and handlers. This guide explains how to choose between them, how hosting plans change the economics and cold-start behaviour of Functions, and the patterns — fan-out, chaining, durable orchestration — that make event-driven systems reliable rather than merely distributed. After reading it you will be able to design a serverless workload that handles retries, duplicates, and poison messages deliberately instead of discovering them in production.

Why This Matters

Serverless removes servers, not failure modes. Events get delivered more than once, handlers time out mid-write, a malformed message retries forever, and a sudden burst of traffic meets a cold start on every new instance. Teams that adopt Functions as "just code" without designing for at-least-once delivery and idempotency build systems that double-charge customers and lose messages silently. The cost model cuts both ways too: per-execution pricing is nearly free at low volume and quietly expensive at sustained high volume, where a container or VM would have cost less. The technology is sound; the failures are architectural.

Core Concepts

The Three Services

ServiceJobReach for it when
Azure FunctionsEvent-driven code executionYou have logic to run: transformations, APIs, processing
Logic AppsWorkflow orchestration and integrationThe work is connecting systems: SaaS connectors, approvals, scheduled business processes
Event GridEvent routing (push pub/sub)Many consumers need the same event, or producers and consumers must be decoupled
Service BusMessaging with ordering and transactionsDelivery must be reliable, ordered, or transactional — queues and topics with sessions

The most common design error is using one service for another's job: hand-writing integration glue in Functions that a Logic Apps connector already implements, or building routing logic into producers that Event Grid exists to absorb.

Azure Functions: Triggers and Bindings

A function runs when its trigger fires — HTTP request, timer, queue message, blob created, Cosmos DB change feed — and bindings declaratively connect inputs and outputs so the function body stays focused on logic.

public static class HttpExample
{
    [FunctionName("HttpExample")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "Pass a name in the query string or request body"
            : $"Hello, {name}";

        return new OkObjectResult(responseMessage);
    }
}

public static class TimerExample
{
    [FunctionName("TimerExample")]
    public static void Run(
        [TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
        ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}

App-level behaviour — timeouts, logging sampling, extension versions — lives in host.json:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "functionTimeout": "00:05:00",
  "healthMonitor": {
    "enabled": true,
    "healthCheckInterval": "00:00:10",
    "healthCheckWindow": "00:02:00",
    "healthCheckThreshold": 3
  }
}

Hosting Plans Decide the Behaviour

The plan is not a pricing detail; it defines the runtime contract. Consumption scales to zero and bills per execution and memory-second, but instances start cold and execution time is bounded. Premium keeps pre-warmed instances, removing most cold starts and allowing VNet integration, for a standing cost. Dedicated (App Service) runs functions on your existing plan — predictable cost, but you manage scaling. Choose by traffic shape: spiky and sparse belongs on Consumption; latency-sensitive or VNet-bound belongs on Premium; steady and high-volume should be cost-compared against containers before defaulting to either.

Logic Apps

Logic Apps defines workflows as JSON (authored in a visual designer) built from triggers, actions, and a large connector library for SaaS and enterprise systems. A minimal request-triggered workflow that calls an API and parses the result:

{
    "definition": {
        "$schema": "https://schema.management.azure.com/schemas/2016-06-01/Microsoft.Logic.json",
        "actions": {
            "HTTP": {
                "type": "Http",
                "inputs": {
                    "method": "GET",
                    "uri": "https://api.example.com/data"
                }
            },
            "Parse_JSON": {
                "type": "ParseJson",
                "inputs": {
                    "content": "@body('HTTP')",
                    "schema": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "value": {
                                "type": "string"
                            }
                        }
                    }
                }
            }
        },
        "triggers": {
            "manual": {
                "type": "Request",
                "kind": "Http"
            }
        }
    }
}

Logic Apps handles retries, run history, and connector authentication for you. Its unit of value is the integration you did not have to write and do not have to maintain.

Event Grid

Event Grid is a push-based event router: publishers post events to topics, subscriptions match them by type and subject filters, and handlers — functions, webhooks, queues — are invoked. Publishing is a small, standard payload:

EventGridEvent[] eventGridEvents = new EventGridEvent[]
{
    new EventGridEvent(
        subject: "ExampleSubject",
        eventType: "Example.EventType",
        dataVersion: "1.0",
        data: new {
            message = "Hello, Event Grid!"
        })
};

string topicEndpoint = "YOUR_TOPIC_ENDPOINT";
string topicKey = "YOUR_TOPIC_KEY";

string topicHostname = new Uri(topicEndpoint).Host;
TopicCredentials topicCredentials = new TopicCredentials(topicKey);
EventGridClient client = new EventGridClient(topicCredentials);

await client.PublishEventsAsync(topicHostname, eventGridEvents);

Delivery is at-least-once with retries and dead-lettering to storage. Handlers must therefore be idempotent — the same event arriving twice is normal operation, not an anomaly — and subscriptions should configure dead-letter destinations from the start so failed events are inspectable instead of dropped.

Patterns

PatternShapeUse case
Fan-outEvent Grid to several functions in parallelIndependent reactions to one event: notify, index, archive
ChainingFunction output triggers the next stepSequential processing pipelines
Durable orchestrationDurable Functions orchestrator + activitiesLong-running, stateful workflows in code: sagas, approvals, fan-out/fan-in with state
Command queueService Bus queue to a functionWork that must not be lost, with ordering or duplicate detection

Durable Functions deserves emphasis: when a workflow has steps, waits, and compensation logic, an orchestrator function expresses it in code with state managed by the framework, instead of a tangle of queues and correlation IDs.

Reliability and Performance Practices

  • Idempotency first: deduplicate on a business key before applying side effects.
  • Dead-letter everything: queues and event subscriptions alike; a poison message should park, not retry forever.
  • Reuse connections: create HttpClient and database clients once, statically — per-invocation creation exhausts sockets under load.
  • Keep functions small and single-purpose: one trigger, one job; composition happens in the architecture, not inside the handler.
  • Watch cold starts where they matter: if p95 latency includes cold starts your users can feel, that is a plan decision (Premium), not a code optimisation.
  • Monitoring

    Wire functions to Application Insights from the start; custom metrics around business operations make failures visible in business terms:

    public static class MonitoringExample
    {
        [FunctionName("MonitoringExample")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
            ILogger log,
            TelemetryClient telemetryClient)
        {
            telemetryClient.TrackEvent("FunctionInvoked");
    
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            try
            {
                // Function logic here
                telemetryClient.TrackMetric("FunctionDuration", stopwatch.ElapsedMilliseconds);
                return new OkResult();
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                throw;
            }
        }
    }

    Decision Framework

    SituationRecommendation
    Custom logic triggered by events or HTTPAzure Functions
    Workflow mostly connecting SaaS and enterprise systems, with approvalsLogic Apps
    Long-running stateful workflow expressed in codeDurable Functions
    Many independent consumers of the same eventsEvent Grid in front of the handlers
    Messages that must be ordered, transactional, or deduplicated by the brokerService Bus queues/topics feeding functions
    Latency-sensitive API with steady trafficPremium plan functions — or a container/API service after a cost comparison

    Implementation Checklist

  • [ ] Every handler is idempotent, with deduplication on a business key where duplicates cause harm
  • [ ] Dead-letter destinations configured on all queues and event subscriptions, with an alert on dead-letter volume
  • [ ] Hosting plan chosen from traffic shape; cold-start impact measured, not guessed
  • [ ] Secrets in Key Vault, accessed via managed identity; no connection strings in app settings where avoidable
  • [ ] Application Insights connected; alerts on failure rate and dead letters, not just availability
  • [ ] Retry policies reviewed per trigger — defaults are not a design
  • [ ] Timeout and memory settings tuned from observed executions, not left at defaults
  • [ ] Load test includes a burst, verifying scale-out behaviour and downstream throttling
  • Trade-offs

    Serverless trades operational control for elasticity. You cannot tune the host, guarantee warm instances on Consumption, or run executions beyond plan limits — long-running work must be decomposed or moved to Durable Functions or another host. Debugging distributed event flows is harder than debugging a monolith: one user action may traverse five functions, and only correlation IDs and Application Insights hold the story together. Vendor coupling is real too — triggers, bindings, and Logic Apps connectors are Azure-shaped, so portability is limited by design.

    When Not to Use

  • Functions on Consumption are the wrong choice for consistently high-throughput APIs; per-execution pricing and cold starts both work against you. Price a Premium plan or a container service honestly.
  • Logic Apps is the wrong choice for compute-heavy or latency-critical processing; it orchestrates, it does not compute. Call a function or service for the heavy step.
  • Event Grid is the wrong choice when delivery must be ordered or transactional; that is Service Bus's job.
  • Serverless in general is the wrong choice for a simple, steady, always-on workload whose traffic never varies — a small container or App Service instance will be cheaper and simpler to reason about.
  • Conclusion

    Use each serverless service for its actual job: Functions for code, Logic Apps for integration, Event Grid for routing, Service Bus for guarantees, and Durable Functions when the workflow itself has state. Design for duplicate delivery and dead letters from the first handler, and choose the hosting plan from the traffic shape. Do those things and serverless delivers its promise — scale without server operations; skip them and you have rebuilt the monolith's failure modes across more moving parts.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.