StackPractices
advanced By Mathias Paulenko

Serverless Function Composition Pattern

Chain serverless functions via Step Functions or orchestration layers to build multi-step workflows with retries, branching, and state management.

Overview

Function composition chains serverless functions into a coordinated workflow. Instead of one large function doing everything, each function owns a single step. An orchestrator (AWS Step Functions, Azure Durable Functions, or a custom orchestrator) runs the sequence, handles retries, branches on conditions, and keeps state between steps.

A single function has hard limits: execution timeouts, no state between calls, no retries across function boundaries. This pattern fills that gap. Break the work into steps and hand them to an orchestrator, and you get visibility, error handling, and the option to replay just the step that failed.

When to Use

  • Business processes like order processing or ETL pipelines, where state has to carry across steps
  • Workflows with conditional branching (approve/reject, retry on failure)
  • You need retries and timeouts per step, not just at the function level
  • Long-running processes that exceed single-function execution limits
  • Different teams own different steps of the same workflow

When NOT to use it: if your flow is one or two steps, or a synchronous request-response where the caller is waiting, an orchestrator adds cost and latency for nothing — direct invocation or a single function is enough. Event-driven chains (the fanout pattern) also fit better when there’s no shared state between consumers.

Solution

AWS Step Functions with Python (CDK)

from aws_cdk import (
    Stack,
    Duration,
    aws_stepfunctions as sfn,
    aws_stepfunctions_tasks as tasks,
    aws_lambda as lambda_,
)
from constructs import Construct

class OrderProcessingStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs):
        super().__init__(scope, construct_id, **kwargs)

        # Define Lambda functions for each step
        validate_order = lambda_.Function(
            self, "ValidateOrder",
            runtime=lambda_.Runtime.PYTHON_3_12,
            handler="validate.handler",
            code=lambda_.Code.from_asset("lambda/order"),
            timeout=Duration.seconds(30),
        )

        process_payment = lambda_.Function(
            self, "ProcessPayment",
            runtime=lambda_.Runtime.PYTHON_3_12,
            handler="payment.handler",
            code=lambda_.Code.from_asset("lambda/payment"),
            timeout=Duration.seconds(60),
        )

        reserve_inventory = lambda_.Function(
            self, "ReserveInventory",
            runtime=lambda_.Runtime.PYTHON_3_12,
            handler="inventory.handler",
            code=lambda_.Code.from_asset("lambda/inventory"),
            timeout=Duration.seconds(30),
        )

        send_notification = lambda_.Function(
            self, "SendNotification",
            runtime=lambda_.Runtime.PYTHON_3_12,
            handler="notify.handler",
            code=lambda_.Code.from_asset("lambda/notification"),
            timeout=Duration.seconds(15),
        )

        refund_payment = lambda_.Function(
            self, "RefundPayment",
            runtime=lambda_.Runtime.PYTHON_3_12,
            handler="refund.handler",
            code=lambda_.Code.from_asset("lambda/payment"),
            timeout=Duration.seconds(60),
        )

        # Build the state machine
        validate_task = tasks.LambdaInvoke(
            self, "ValidateOrderTask",
            lambda_function=validate_order,
            output_path="$.Payload",
        )

        payment_task = tasks.LambdaInvoke(
            self, "ProcessPaymentTask",
            lambda_function=process_payment,
            output_path="$.Payload",
            retry_on_service_exceptions=True,
        )

        inventory_task = tasks.LambdaInvoke(
            self, "ReserveInventoryTask",
            lambda_function=reserve_inventory,
            output_path="$.Payload",
        )

        notify_task = tasks.LambdaInvoke(
            self, "SendNotificationTask",
            lambda_function=send_notification,
            output_path="$.Payload",
        )

        refund_task = tasks.LambdaInvoke(
            self, "RefundPaymentTask",
            lambda_function=refund_payment,
            output_path="$.Payload",
        )

        # Define workflow with branching and error handling
        definition = (
            validate_task
            .next(payment_task)
            .next(sfn.Choice(self, "PaymentResult")
                .when(
                    sfn.Condition.string_equals("$.paymentStatus", "SUCCESS"),
                    inventory_task.next(notify_task)
                )
                .when(
                    sfn.Condition.string_equals("$.paymentStatus", "FAILED"),
                    refund_task.next(sfn.Fail(self, "OrderFailed",
                        error="PaymentFailed",
                        cause="Payment processing failed"
                    ))
                )
                .otherwise(sfn.Fail(self, "UnknownPaymentStatus"))
            )
        )

        sfn.StateMachine(
            self, "OrderProcessingStateMachine",
            definition=definition,
            timeout=Duration.minutes(5),
        )

Lambda Handler (Python)

def handler(event, context):
    order_id = event.get("orderId")
    customer_id = event.get("customerId")
    items = event.get("items", [])
    total = event.get("total", 0)

    if not order_id or not customer_id or not items:
        return {
            "statusCode": 400,
            "error": "INVALID_ORDER",
            "message": "Missing required fields"
        }

    if total <= 0:
        return {
            "statusCode": 400,
            "error": "INVALID_TOTAL",
            "message": "Total must be positive"
        }

    return {
        "statusCode": 200,
        "orderId": order_id,
        "customerId": customer_id,
        "items": items,
        "total": total,
        "validated": True
    }

TypeScript with AWS SDK

import { SFNClient, StartExecutionCommand } from '@aws-sdk/client-sfn';

const sfnClient = new SFNClient({ region: 'us-east-1' });

interface OrderRequest {
  orderId: string;
  customerId: string;
  items: Array<{ productId: string; quantity: number; price: number }>;
  total: number;
}

async function startOrderWorkflow(order: OrderRequest): Promise<string> {
  const command = new StartExecutionCommand({
    stateMachineArn: process.env.ORDER_STATE_MACHINE_ARN!,
    input: JSON.stringify(order),
    name: `order-${order.orderId}-${Date.now()}`,
  });

  const response = await sfnClient.send(command);
  return response.executionArn!;
}

// Check execution status
import { DescribeExecutionCommand } from '@aws-sdk/client-sfn';

async function getWorkflowStatus(executionArn: string): Promise<{
  status: string;
  output?: any;
  error?: string;
}> {
  const command = new DescribeExecutionCommand({ executionArn });
  const response = await sfnClient.send(command);

  return {
    status: response.status!,
    output: response.output ? JSON.parse(response.output) : undefined,
    error: response.error,
  };
}

Azure Durable Functions (TypeScript)

import * as df from 'durable-functions';
import { AzureFunction, Context } from '@azure/functions';

const orchestrator: df.Orchestrator = df.orchestrator(function* (context):
  Generator<any, any, any> {

  const order = context.df.getInput();

  // Step 1: Validate
  const validationResult = yield context.df.callActivity('ValidateOrder', order);
  if (!validationResult.valid) {
    return { status: 'FAILED', error: validationResult.error };
  }

  // Step 2: Process payment (with retry)
  const paymentResult = yield context.df.callActivityWithRetry(
    'ProcessPayment',
    {
      retryOptions: {
        firstRetryIntervalInMilliseconds: 5000,
        maxNumberOfAttempts: 3,
      },
    },
    { orderId: order.orderId, total: order.total }
  );

  if (paymentResult.status !== 'SUCCESS') {
    // Compensating action: refund
    yield context.df.callActivity('RefundPayment', { orderId: order.orderId });
    return { status: 'FAILED', error: 'PaymentFailed' };
  }

  // Step 3: Reserve inventory (parallel for multiple items)
  const inventoryResults = yield context.df.Task.all(
    order.items.map((item: any) =>
      context.df.callActivity('ReserveItem', { productId: item.productId, quantity: item.quantity })
    )
  );

  const allReserved = inventoryResults.every((r: any) => r.reserved);
  if (!allReserved) {
    yield context.df.callActivity('RefundPayment', { orderId: order.orderId });
    return { status: 'FAILED', error: 'InventoryUnavailable' };
  }

  // Step 4: Send notification
  yield context.df.callActivity('SendNotification', {
    customerId: order.customerId,
    message: `Order ${order.orderId} confirmed`,
  });

  return { status: 'SUCCESS', orderId: order.orderId };
});

df.app.orchestrate('OrderOrchestrator', orchestrator);

Explanation

The composition pattern separates orchestration from execution:

  1. Orchestrator — defines the workflow as a state machine. It holds the step order, branching conditions, and each step’s retry policy and timeout. The orchestrator itself is stateless: it reads state from a managed store (Step Functions, Durable Functions).

  2. Step functions — each Lambda or Activity handles one unit of work. The orchestrator hands it input, it does its job, and it returns output — with no idea that other steps exist.

  3. State management — the orchestrator passes data between steps. Whatever a step returns flows into the next one. The orchestrator persists that state, so when a step fails the workflow resumes from the last successful step.

  4. Error handling — retry behavior lives on each step (say, 3 attempts with exponential backoff). Once a step exhausts its retries, the workflow can branch to a compensation step (e.g. refund) or fail cleanly.

flowchart diagram: START([Order event

Variants

ApproachOrchestratorBest For
AWS Step FunctionsManaged state machineAWS-native workflows
Azure Durable FunctionsCode-based orchestratorAzure-native workflows
EventBridge + LambdaEvent-driven chainingSimple sequences, no state
Custom orchestrator (Lambda)Self-builtComplex custom logic
Chained Lambda (direct invoke)Function-to-functionSimple 2-3 step flows

Best Practices

  • For a deeper guide, see Serverless Warm Pool Pattern. For the consumer-side implementation, the Step Functions workflow recipe walks through a complete setup.

  • Keep steps idempotent — the orchestrator may retry a step. Running it once or five times must leave the system in the same state. Use idempotency keys for payment and inventory operations.

  • Use compensation steps — if a step fails after side effects (e.g. payment succeeded but inventory failed), add a compensation step (e.g. refund) to roll back.

  • Set per-step timeouts — give every step its own timeout, so a stuck step doesn’t hold the whole workflow hostage.

  • Monitor execution history — workflow duration, per-step failure rates, retry counts — CloudWatch or Application Insights cover it.

  • Keep orchestrator logic declarative — define the workflow as a state machine, not imperative code — easier to draw, easier to debug, easier to change.

Common Mistakes

  • Chaining functions directly — calling Lambda from Lambda skips the orchestrator — and with it go state, retries, and visibility. Use Step Functions or Durable Functions.
  • Non-idempotent steps — if a step charges a credit card and is retried, the customer is charged twice. Use idempotency keys.
  • No compensation logic — when a step fails after side effects, the system is left in an inconsistent state. Always define compensation steps for workflows with side effects.
  • Over-orchestration — don’t use Step Functions for a simple 2-step process. Direct invocation or EventBridge is simpler and cheaper.
  • Passing large payloads between steps — Step Functions has a 256KB payload limit. Pass references (S3 keys, database IDs) instead of full data.

Troubleshooting

  • Execution fails at the Choice state: the string_equals path doesn’t match what the task actually returns. Log the real state input — output_path="$.Payload" unwraps the Lambda response, so $.paymentStatus has to sit at the top level of your handler’s return value.
  • States.TaskFailed with no useful message: the Lambda raised an unhandled exception. Check the function’s logs for that execution’s timestamp; Step Functions only surfaces the error name.
  • Payload too large for the next state: Step Functions caps state input/output at 256KB. Pass an S3 key or a database ID between steps instead of the full payload.
  • A step keeps retrying and burning money: your retry policy matches a non-retryable error (a 400 INVALID_ORDER will never succeed on retry). Narrow retry_on_service_exceptions or add a Catch that routes validation errors straight to Fail.
  • Execution name collision on StartExecution: execution names stay unique per state machine for 90 days. Include the order ID plus a timestamp or UUID, as the example does.

Further Reading

Frequently Asked Questions

What is the difference between orchestration and choreography?

In orchestration, a central orchestrator (Step Functions) controls the workflow and invokes steps. In choreography, each function emits events that trigger other functions, with no central controller. Orchestration wins on debugging and monitoring; choreography wins on decoupling and scale.

When should I use Step Functions vs direct Lambda invocation?

Use Step Functions when your workflow has branching, retries, or state to carry between steps. Use direct invocation for simple 1-2 step processes where the caller can handle errors. Step Functions cost more but provide visibility and reliability.

How do I handle long-running workflows?

Express Workflows cap at 5 minutes; Standard Workflows run for up to a year. For long-running workflows, use Standard and break them into stages with human approval steps or wait states.

Can I version workflows without breaking in-flight executions?

Yes. Step Functions supports versioning. When you update a state machine, in-flight executions continue on the old version. New executions use the updated version. This allows zero-downtime deployments.