0xOX0X
Cloud & SaaS

Run 30-Minute AWS Jobs With Safe Lambda Checkpoints

Quick Answer

Return 202 Accepted with a job ID instead of waiting for the report to finish. Use a Standard Step Functions workflow to run bounded Lambda slices and save progress in DynamoDB. If the work needs one continuous process, use a container task instead.

By Devon ReedUpdated 2026-12-015 min read
A job receipt returns immediately while three AWS Lambda slices save checkpoints and assemble a report (Lambda checkpoints)

Your report request times out, but the job keeps running. Return 202 Accepted with a job ID instead of making the request wait: a Standard Step Functions workflow can run the job in bounded Lambda slices and save progress between them. If the work needs one continuous process, use a container task instead.

Separate the HTTP timeout from the job timeout

Three timing tracks distinguish an HTTP integration limit, an ALB idle timeout, and the AWS Lambda invocation cap

As of June 2025, AWS’s REST API quotas list a 29-second integration timeout for edge-optimized REST APIs; Regional and private REST APIs can request a higher limit. HTTP APIs have a 30-second maximum integration timeout. An ALB’s 4,000-second upper bound is for the idle-timeout setting, not an overall request deadline. More Lambda memory may speed up a slice, but it won’t extend the 900-second invocation limit.

OptionWhat bounds the runChoose it when
Standard Step Functions + LambdaWorkflow: up to one year, subject to execution-history quotas; each invocation: 15 minutesInput can be partitioned and output can be replayed safely
Express Step FunctionsWorkflow: five minutesThe whole workflow is short; not a fit for this job
ECS task on FargateTask lifecycle: process exit, task stop, or infrastructure interruption; no Lambda invocation capSlicing would repeat expensive setup or break a continuous operation
AWS Batch on EC2 or FargateConfigured attempt timeout and compute lifecycle; don’t count on Fargate jobs running beyond 14 daysYou need a queue and managed scheduling across many jobs

Duration references, as of June 2025: Step Functions quotas and AWS Batch job timeouts.

Build a staging job you can replay

An authenticated API starts AWS Step Functions; a Lambda worker saves checkpoints and the workflow routes failures

  1. Create a DynamoDB table with string partition key pk and a standard SQS failure queue. Package this Python module in two Lambdas: app.submit behind an authenticated HTTP API POST /jobs route, and app.work with a 900-second timeout. Set FLOW on the submitter and TABLE on the worker. Scope IAM to the named workflow, worker, table, and queue: the submitter starts executions, the worker reads and writes items, and the workflow invokes the worker and sends failure messages.
python
# app.py
import json
import os
import uuid

import boto3
from botocore.config import Config

def submit(event, context):
    job = uuid.uuid4().hex
    boto3.client('stepfunctions').start_execution(
        stateMachineArn=os.environ['FLOW'], name=job,
        input=json.dumps({'jobId': job}))
    return {'statusCode': 202, 'headers': {'content-type': 'application/json'},
            'body': json.dumps({'jobId': job})}

def work(event, context):
    table = boto3.resource('dynamodb', config=Config(
        connect_timeout=2, read_timeout=3,
        retries={'total_max_attempts': 2})).Table(os.environ['TABLE'])
    conflict = table.meta.client.exceptions.ConditionalCheckFailedException
    job = event['jobId']
    key = {'pk': f'J#{job}'}
    old = int(table.get_item(Key=key, ConsistentRead=True)
              .get('Item', {}).get('cursor', 0))

    def insert(item):
        try:
            table.put_item(Item=item, ConditionExpression='attribute_not_exists(pk)')
            return True
        except conflict:
            return False

    if event.get('fault') == 'terminal':
        raise RuntimeError('Staging terminal failure')
    cursor = old
    while cursor < min(old + 100, 300):
        if context.get_remaining_time_in_millis() < 60_000:
            break
        insert({'pk': f'R#{job}#{cursor}', 'result': cursor * cursor})
        cursor += 1
    if cursor == old and cursor < 300:
        raise RuntimeError('Slice made no progress')

    condition = '(attribute_not_exists(pk) OR #c = :old)'
    if event.get('fault') == 'checkpoint' and insert({'pk': f'F#{job}'}):
        condition += ' AND attribute_exists(staging_blocker)'
    try:
        table.put_item(Item={**key, 'cursor': cursor},
                       ConditionExpression=condition,
                       ExpressionAttributeNames={'#c': 'cursor'},
                       ExpressionAttributeValues={':old': old})
    except conflict as exc:
        raise RuntimeError('Checkpoint write rejected') from exc
    return {'done': cursor == 300}
  1. Create a Standard state machine from this definition and replace both placeholders. The definition uses JSONata expressions. Use a published worker version ARN. The task replaces its previous slice result, so the workflow loops without accumulating results in its payload.
json
{
  "QueryLanguage": "JSONata",
  "StartAt": "Slice",
  "States": {
    "Slice": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Arguments": {"FunctionName": "REPLACE_WORKER_VERSION_ARN", "Payload": "{% $states.input %}"},
      "Output": "{% $merge([$states.input, {'slice': {'done': $states.result.Payload.done}}]) %}",
      "Retry": [{"ErrorEquals": ["RuntimeError", "Lambda.ServiceException", "Lambda.TooManyRequestsException"], "IntervalSeconds": 2, "BackoffRate": 2, "MaxAttempts": 2}],
      "Catch": [{"ErrorEquals": ["States.ALL"], "Output": "{% $merge([$states.input, {'error': $states.errorOutput}]) %}", "Next": "QueueFailure"}],
      "Next": "Finished"
    },
    "Finished": {"Type": "Choice", "Choices": [{"Condition": "{% $states.input.slice.done = true %}", "Next": "Done"}], "Default": "Slice"},
    "Done": {"Type": "Succeed"},
    "QueueFailure": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sqs:sendMessage",
      "Arguments": {"QueueUrl": "REPLACE_FAILURE_QUEUE_URL", "MessageBody": "{% $string($states.input) %}"},
      "Next": "Failed"
    },
    "Failed": {"Type": "Fail"}
  }
}
  1. Submit a job in staging. Check execution history and read its checkpoint with the command below. The cursor always means next zero-based index; an uninterrupted run advances through 100, 200, and 300. For production, index into an immutable input manifest and keep the job ID and index in the output key.
sh
aws dynamodb get-item --table-name "$TABLE" --consistent-read \
  --key "{\"pk\":{\"S\":\"J#$JOB\"}}"

Illustrative Scenario: 1,000 monthly reports

Assume US East (N. Virginia), Linux/x86, no retries, and 30 minutes of useful work per report. At 2 GB, Lambda needs three 600-second slices, not two invocations with no checkpoint headroom. Allow one extra billed second per slice for checkpoint overhead: 3,606,000 GB-seconds, 3,000 requests, and 7,000 Standard transitions (three tasks, three choices, one success state per job).

ArchitectureMonthly compute and orchestration
Lambda + Standard3,606,000 × $0.0000166667 + 3,000 × $0.20/million + 7,000 × $0.025/1,000 ≈ $60.28
Direct ECS Fargate task500 billed task-hours, including startup, at 1 vCPU and 2 GB: 500 × ($0.04048 + 2 × $0.004445) ≈ $24.69

US East (N. Virginia) list rates as of June 2025; the Lambda GB-second rate was unchanged when re-checked in December 2026. Sources: AWS Lambda Pricing, AWS Step Functions Pricing, and AWS Fargate Pricing. Excludes free tiers, discounts, DynamoDB, API Gateway, SQS, logs, registry storage, networking, and any Fargate launcher. Measure billed runtime on both platforms before choosing.

Verification and rollback checklist

A Lambda retry reuses existing output rows after a failed checkpoint write, then advances the cursor without duplicates

  • Replay: Invoke the worker twice concurrently with the same fresh job ID. A retry can repeat work after an output write succeeds but before the checkpoint lands. Verify one output per index and no cursor regression. An external API needs its own idempotency key; a DynamoDB marker alone can’t protect that call.
  • Failed write: Start a staging execution directly with a fresh job ID and "fault":"checkpoint". Verify the first checkpoint write fails after outputs land, then the retry reuses those output keys and completes.
  • Terminal failure: Run with "fault":"terminal"; verify two retries, a failure-queue message, and a failed execution. Alarm on failed executions too, so a broken queue permission can’t hide a failure. Remove fault injection before production.
  • Rollback: Point the submitter at a published workflow version. Shift the staging route back to the previous submitter version, verify new jobs use the old path, and let in-flight jobs finish on their pinned worker. Keep checkpoint formats compatible during the rollout.

Next action: Run the checkpoint-write failure test on one representative staging report before routing production traffic.

Share this article

Frequently Asked Questions

Does adding Lambda memory let an invocation run longer?

No. More memory may speed up a slice, but the invocation limit stays at 15 minutes.

Does 202 Accepted mean the report is ready?

No. It means the workflow accepted the job. Use the job ID to check progress and verify completion.

What does the checkpoint cursor represent?

It is the next zero-based index. In the staging example, an uninterrupted run advances through 100, 200, and 300.

When should you choose an ECS task on Fargate instead of Lambda slices?

Choose it when slicing would repeat expensive setup or break a continuous operation.

Free Weekly Dispatch

Get the Weekly SMB AI & SaaS Brief

Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.