AWS Builder Center

Architectural Blueprint: Building a Resilient, Event-Driven Task Scheduler on AWS

Step-by-step guide to building a serverless, event-driven task scheduler on AWS using EventBridge Scheduler, SQS, Lambda, and DynamoDB. Master distributed state tracking, idempotency, and error handling for scalable background processing.

Computer Science Student
When building distributed systems, offloading background processing from your primary API layer is essential for maintaining low latency and high availability. Whether you are running batch data pipelines, handling periodic database maintenance, or executing retry-heavy asynchronous workflows, a naive Cron setup on a single virtual machine introduces a single point of failure (SPOF).
In this article, we’ll walk through building a resilient, fully serverless event-driven task scheduler using Amazon EventBridge, AWS Lambda, and Amazon SQS, with distributed state tracking managed by Amazon DynamoDB.

Architecture Overview

Instead of maintaining dedicated scheduler instances, our architecture leverages native AWS managed services to decouple time-based event triggers from task execution:
[ Amazon EventBridge Scheduler ]
│
▼
[ AWS Lambda (Dispatcher) ]
│
┌───────┴───────┐
▼ ▼
[ Amazon SQS ] [ Amazon DynamoDB ]
(Task Queue) (Execution State)
│
▼
[ AWS Lambda (Worker) ]

  1. Amazon EventBridge Scheduler: Emits precision time-based events without requiring running compute resources.
  1. Dispatcher Lambda: Validates incoming payloads, updates task status in DynamoDB to  PENDING , and places execution messages onto an SQS queue.
  1. Amazon SQS (Standard or FIFO): Acts as a buffer to handle downstream rate-limiting and spikes in workload volume.
  1. Worker Lambda: Consumes tasks from SQS, executes the core logic, updates state in DynamoDB to  COMPLETED  or  FAILED , and handles retries.

Step 1: Designing the Task State Schema in DynamoDB

To ensure auditability and idempotency, every scheduled task must track its execution lifecycle. We use an Amazon DynamoDB table named  TaskExecutionState  with a Partition Key ( task_id ) and Sort Key ( timestamp ).

Single-Table Item Structure

{
"task_id": "CRON_SYNC_USER_DATA_001",
"timestamp": 1772582400,
"status": "PENDING",
"retry_count": 0,
"payload": {
"target_region": "us-east-1",
"batch_size": 500
},
"ttl": 1775174400
}

>Tip: Always set a Time to Live (TTL) attribute on transient execution records to automatically prune old logs from DynamoDB at zero cost.


Step 2: Implementing the Dispatcher Function

The Dispatcher validates execution requests, logs the initial state dynamically using DynamoDB conditional writes, and dispatches the task payload to SQS.

import os
import json
import time
import boto3

dynamodb = boto3.resource('dynamodb')
sqs = boto3.client('sqs')

TABLE_NAME = os.environ['TASK_TABLE_NAME']
QUEUE_URL = os.environ['QUEUE_URL']

def lambda_handler(event, context):
table = dynamodb.Table(TABLE_NAME)
task_id = event.get('task_id')
payload = event.get('payload', {})
current_time = int(time.time())
# 1. Record PENDING state with conditional check to ensure idempotency
try:
table.put_item(
Item={
'task_id': task_id,
'timestamp': current_time,
'status': 'PENDING',
'retry_count': 0,
'payload': payload,
'ttl': current_time + (30 * 86400) # 30-day retention
},
ConditionExpression='attribute_not_exists(task_id) OR #st IN (:comp, :fail)',
ExpressionAttributeNames={'#st': 'status'},
ExpressionAttributeValues={':comp': 'COMPLETED', ':fail': 'FAILED'}
)
except dynamodb.meta.client.exceptions.ConditionalCheckFailedException:
return {
'statusCode': 409,
'body': json.dumps(f"Task {task_id} is already in execution.")
}

# 2. Enqueue task for worker consumption
sqs.send_message(
QueueUrl=QUEUE_URL,
MessageBody=json.dumps({
'task_id': task_id,
'timestamp': current_time,
'payload': payload
})
)
return {
'statusCode': 200,
'body': json.dumps(f"Task {task_id} successfully queued.")
}

Step 3: Reliable Processing & Error Handling with SQS Batching

When configuring the Worker Lambda to consume from SQS, configure Report Batch Item Failures ( ReportBatchItemFailures ). This ensures that if a single record within an SQS message batch fails, only that specific message is returned to the queue rather than re-processing the entire batch.

import os
import json
import boto3
dynamodb = boto3.resource('dynamodb')
TABLE_NAME = os.environ['TASK_TABLE_NAME']
def process_task(payload):
# Place core execution logic here (e.g., API calls, DB cleanup)
# Return True on success, throw Exception on failure
return True
def lambda_handler(event, context):
table = dynamodb.Table(TABLE_NAME)
batch_item_failures = []

for record in event['Records']:
message_id = record['messageId']
body = json.loads(record['body'])
task_id = body['task_id']
timestamp = body['timestamp']
try:
# Execute business logic
process_task(body['payload'])
# Update state to COMPLETED
table.update_item(
Key={'task_id': task_id, 'timestamp': timestamp},
UpdateExpression="SET #st = :val",
ExpressionAttributeNames={'#st': 'status'},
ExpressionAttributeValues={':val': 'COMPLETED'}
)
except Exception as e:
# Mark failing record to return to SQS for automatic retry
batch_item_failures.append({"itemIdentifier": message_id})
# Update state in DynamoDB
table.update_item(
Key={'task_id': task_id, 'timestamp': timestamp},
UpdateExpression="SET #st = :val, last_error = :err ADD retry_count :inc",
ExpressionAttributeNames={'#st': 'status'},
ExpressionAttributeValues={
':val': 'RETRYING',
':err': str(e),
':inc': 1
}
)

return {"batchItemFailures": batch_item_failures}


Conclusion

By decoupling schedule triggers from task execution using EventBridge, SQS, Lambda, and DynamoDB, you build a self-healing, highly scalable background execution engine. This pattern eliminates infrastructure management, reduces idle compute costs to zero, and ensures that failing tasks are systematically captured and retried.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article