DEV Community

Cover image for The Event-Driven Agent Trap: Solving At-Least-Once Replays, Context Corruption, and Double-Execution in Production AWS AI Pipelines
Md Zubair
Md Zubair

Posted on Originally published at builder.aws.com

The Event-Driven Agent Trap: Solving At-Least-Once Replays, Context Corruption, and Double-Execution in Production AWS AI Pipelines

Building autonomous agents that run multi-step workflows across AWS is intoxicating. You wire an Amazon Bedrock model to a set of Lambda action groups, hook up Amazon EventBridge or SQS to orchestrate events asynchronously, and watch the system execute complex tasks with minimal human intervention.

In development, everything works cleanly. You fire a synthetic event, the agent reasons through its tool catalog, executes Step A, writes to DynamoDB, and finishes.

Then you ship to production.

At 2:00 AM, a momentary network blip occurs between your downstream API and your worker Lambda. Amazon EventBridge triggers its standard retry policy. SQS visibility timeouts expire under heavy load. A transient 504 gateway timeout causes your upstream orchestration to reissue an invocation.

Suddenly:

  • An agent executes the same payment or external booking action twice.
  • An agent's working memory (context window) gets corrupted by duplicate historical state messages.
  • Step Functions executions spawn runaway parallel branches because each retry was treated as a novel, independent incident.

In traditional microservices, non-idempotent operations are bad. In agentic AI architectures, non-idempotent operations are catastrophic. When an LLM observes a duplicate execution or a partially mutated environment, it doesn't just error out—it hallucinates, misattributes state changes, and attempts invalid recovery steps that amplify the damage.

Here is the exact architectural blueprint we use at Zubair Systems to enforce deterministic execution, idempotency, and poison-pill resilience across high-scale agent workflows on AWS.


The Root Problem: Why AI Agents Break Under At-Least-Once Delivery

Distributed cloud systems rely on at-least-once delivery guarantees. EventBridge, SQS, and SNS guarantee that your message will arrive, but they do not guarantee it will arrive only once. Under high concurrency, cross-region replication, or transient failure recovery, duplicate events are not edge cases—they are an operational mathematical certainty.

For deterministic code (e.g., standard CRUD updates), idempotency is solved with database primary keys or unique constraint indices (UPSERT).

However, autonomous agents introduce three unique failure modes:

Failure Mode How It Happens Systemic Impact
Double-Action Dispatch An agent's tool call (e.g., charge card, provision EC2, send Slack alert) succeeds, but the Lambda response times out before EventBridge receives an ACK. EventBridge replays the event. Customer gets double-charged; duplicate infrastructure is created.
Context Split-Brain The agent’s conversation transcript / action log is appended to twice. The LLM sees two identical user intents or tool outputs back-to-back. LLM concludes the first attempt failed, apologizes for nonexistent failures, and mutates downstream records incorrectly.
Cascading Poison Replays A malformed prompt or unhandled API payload causes the agent Lambda to crash or exceed timeout. SQS or EventBridge retries up to maximum attempts. Unbounded token spend, exhausted Bedrock quotas, and massive latency spikes for healthy events.

Pattern 1: The Two-Layer Idempotency Guard (DynamoDB + Step Functions)

The most robust way to prevent duplicate agent execution is a strict two-layer isolation gate:

[ Incoming EventBridge Event ]
             │
             ▼
  ┌──────────────────────────────────────────────┐
  │ Layer 1: Lambda Trigger                      │
  │ • Extract incident_id + job_run_id           │
  │ • DynamoDB Conditional Put:                  │
  │   attribute_not_exists(idempotency_key)      │
  │ • Attach TTL (e.g., 24 hours)                │
  └──────────────────────┬───────────────────────┘
                         │
          ┌──────────────┴──────────────┐
          │ (First-Time Seen)           │ (Duplicate / In-Flight)
          ▼                             ▼
  ┌────────────────────────┐    ┌────────────────────────┐
  │ Layer 2: Step Functions│    │ Immediate Return 200   │
  │ • Deterministic Name:  │    │ Drop duplicate event   │
  │   `agent-${hash}`      │    │ Zero re-execution      │
  └────────────────────────┘    └────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Layer 1: DynamoDB Conditional Write with TTL

Before your worker Lambda invokes Amazon Bedrock or instantiates an AgentCore session, it must claim an exclusive execution lock inside DynamoDB using attribute_not_exists.

import boto3
import os
import time
from botocore.exceptions import ClientError

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["IDEMPOTENCY_TABLE_NAME"])

def acquire_execution_lock(incident_id: str, job_run_id: str, ttl_seconds: int = 86400) -> bool:
    """
    Acquires an atomic execution lock.
    Returns True if this is the first execution, False if duplicate.
    """
    idempotency_key = f"LOCK#{incident_id}#{job_run_id}"
    now = int(time.time())

    try:
        table.put_item(
            Item={
                "idempotency_key": idempotency_key,
                "incident_id": incident_id,
                "job_run_id": job_run_id,
                "status": "IN_PROGRESS",
                "created_at": now,
                "expires_at": now + ttl_seconds
            },
            ConditionExpression="attribute_not_exists(idempotency_key)"
        )
        return True
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            # Duplicate execution attempt intercepted cleanly!
            print(f"[IDEMPOTENCY_GUARD] Dropped duplicate event for key: {idempotency_key}")
            return False
        raise e
Enter fullscreen mode Exit fullscreen mode

Why the TTL matters: If a hard failure or Lambda OOM happens before the lock can transition to COMPLETED, the TTL ensures stale keys automatically clean themselves up, avoiding manual administrative intervention.

Layer 2: Deterministic Step Functions Execution Names

What happens if the DynamoDB lock succeeds, but your orchestration layer crashes halfway through starting AWS Step Functions?

AWS Step Functions provides an invaluable built-in idempotency guarantee: execution names are unique per AWS account, region, and state machine within a 90-day window. If you call StartExecution with an execution name that already ran (or is currently running) with identical execution input, Step Functions returns the existing execution ARN without starting a new one.

import hashlib
import json

sfn_client = boto3.client("stepfunctions")

def start_idempotent_agent_execution(state_machine_arn: str, incident_id: str, payload: dict):
    # Create a deterministic, normalized hash from incident ID and payload
    payload_serialized = json.dumps(payload, sort_keys=True)
    deterministic_hash = hashlib.sha256(f"{incident_id}-{payload_serialized}".encode()).hexdigest()[:32]
    execution_name = f"exec-{incident_id}-{deterministic_hash}"

    response = sfn_client.start_execution(
        stateMachineArn=state_machine_arn,
        name=execution_name,
        input=payload_serialized
    )
    return response["executionArn"]
Enter fullscreen mode Exit fullscreen mode

Even if EventBridge retries hit Lambda multiple times, Layer 1 drops them immediately, and Layer 2 ensures the underlying state machine is physically incapable of double-executing.


Pattern 2: Guarding Tool Actions with Deterministic Action Receipts

Even with workflow-level idempotency, individual agent tool actions (Action Groups in Amazon Bedrock) can still fail mid-sequence.

For example: an agent decides to call provision_database_table, followed by notify_team. The database call succeeds, but the network drops before the agent gets the response. The agent re-reasons: "I need to provision the database table," and attempts to create it again.

To safeguard tool actions:

  1. Deterministic Action Hashes: Every tool request generates a hash of (conversation_id, step_index, tool_name, tool_parameters).
  2. Action Receipts Table: Action Groups check DynamoDB before executing side effects. If an action receipt exists for that exact step hash, the tool immediately returns the cached result without invoking downstream APIs.
Agent Action -> Check Action Receipt (DynamoDB)
                  ├─ Found -> Return Cached Tool Response (Zero Side-Effects)
                  └─ Not Found -> Execute API -> Save Action Receipt -> Return Result
Enter fullscreen mode Exit fullscreen mode

This ensures that even inside an iterative ReAct reasoning loop, tool execution is strictly idempotent.


Pattern 3: Poison-Pill Quarantine and Circuit Breakers

In autonomous agent systems, a "poison pill" is an input payload that causes an LLM to generate an unparseable response, trigger a recursive tool-calling loop, or exceed context window limits on every retry.

If you leave default retry configurations on your SQS queues or EventBridge rules, a single poison pill can burn through thousands of dollars of API tokens in minutes.

1. MaxReceiveCount and Dead-Letter Queue (DLQ)

Enforce a strict maxReceiveCount = 2 on your Amazon SQS agent input queue. If an agent fails to process a payload twice, send it directly to an Amazon SQS Dead-Letter Queue (DLQ).

2. CloudWatch Metric Filter on FailedExecution

Create a CloudWatch Metric Filter scanning for [ERROR] [AGENT_FAILURE] or Step Functions ExecutionsFailed. Attach a CloudWatch Alarm with an Amazon SNS topic that:

  • Immediately disables the EventBridge rule if failure rates exceed 5% over a 3-minute window (Circuit Breaker).
  • Sends a high-priority alert to the platform on-call engineer with the execution trace and poison payload.

The Production Architecture Blueprint

Here is how all these pieces fit together in a high-resiliency AWS environment:

[ Client / Webhook ]
        │
        ▼
[ Amazon EventBridge / API Gateway ]
        │
        ▼
[ SQS FIFO Input Queue (MessageGroupId = incident_id) ]
        │
        ▼
[ Ingestion Lambda Worker ]
   ├──> 1. Acquire DynamoDB Lock (attribute_not_exists)
   ├──> 2. Calculate Deterministic Execution Hash
   └──> 3. Start AWS Step Functions (Deterministic Name)
            │
            ▼
   [ AWS Step Functions Workflow ]
      ├── Step A: Bedrock AgentCore Reasoning Session
      ├── Step B: Action Group Execution (Guarded by Action Receipts)
      ├── Step C: Deterministic MERGE / S3 Checkpoint
      └── Step D: Release / Finalize DynamoDB Lock
Enter fullscreen mode Exit fullscreen mode

Key Takeaways for Cloud & AI Builders

  1. Never trust standard retry policies with generative agents. At-least-once delivery will cause double-billing and tool corruption unless gated by atomic conditional locks.
  2. Layer your defenses. Use DynamoDB conditional writes (attribute_not_exists) with TTL as your fast-rejection gate, backed by deterministic Step Functions execution names as the structural fallback.
  3. Cache tool execution receipts. Make your Agent Action Groups idempotent by keying tool results to deterministic action hashes.
  4. Treat poison pills as security incidents. Cap retries aggressively (max 2), route failures to DLQs, and implement CloudWatch automated circuit breakers to protect both your infrastructure and your LLM budget.

Production reliability in agentic AI isn’t about hoping models don't fail—it’s about ensuring that when failure happens, your cloud architecture makes duplicate execution mathematically impossible.


What idempotency or retry patterns are you implementing in your AWS agent stacks ahead of AWS re:Invent 2026? Let's discuss in the comments below!

Top comments (0)