AWS – 20 Production Scenarios Every Senior Developer Should Know (with Answers)

Senior AWS interviews often test whether you can reason beyond the happy path. Messaging services are durable and managed, but delivery still depends on filters, permissions, throttling, retries, ordering, visibility, and consumer capacity. Strong answers connect those controls to observable failure modes rather than treating a service as a black box.

This article frames SNS, SQS, EventBridge, and Lambda reliability problems from an operational perspective. It focuses on tracing messages through a fanout, finding hidden queue bottlenecks, preserving safe replay and retry behavior, and designing idempotent side effects when delivery is at least once.

All 20 answers below are free. Want the full set, every answer with a worked example?

Cloud, DevOps & System Design for Java Backend (200 Qs: Docker, Kubernetes, AWS, CI/CD, Terraform, databases, system design)

Get the guide

Section 1: SNS Fanout

1. An SNS subscriber misses alerts. How can you distinguish a filter mismatch from endpoint failure?

First determine whether SNS filtered the notification before delivery, or attempted delivery and received a failure. A filtered message is not a delivery failure: the subscription will show filtering metrics and the endpoint will have no corresponding request or queue message.

The useful distinction is in the per-subscription evidence:

  • A rising NumberOfNotificationsFilteredOut indicates that the message reached SNS but did not satisfy the subscription policy. NumberOfNotificationsFilteredOut-NoMessageAttributes is especially useful when the policy expects attributes that publishers omitted.
  • A delivery failure appears in NumberOfNotificationsFailed, endpoint delivery-status logs, HTTP response or timeout logs, Lambda invocation errors, or an SQS dead-letter queue, depending on the protocol.
  • For an SQS subscription, SNS may have delivered successfully even though the application has not processed the message. Check the queue depth and age, not just the application log.
  • A successful SNS delivery means the endpoint accepted the message. It does not prove that the consumer completed business processing.

In production, investigate in this order:

  1. Record the message ID, topic, subscription, and attribute values from the publisher. Confirm that the published attributes have the expected names and data types.
  2. Check the subscription's filter policy and its filtering metrics for the same time window. Remember that policy changes are not necessarily visible everywhere immediately.
  3. If the message was eligible, inspect SNS delivery metrics and protocol-specific delivery logs. For HTTP, correlate status codes, latency, TLS or DNS errors, and retry attempts. For Lambda, inspect invocation errors and throttles.
  4. For SQS, inspect the target queue, visibility timeout, redrive policy, and consumer logs. For HTTP or Lambda, verify the endpoint's health and configured retry or dead-letter behavior.
  5. Fix the policy or publisher schema for a filter mismatch; repair or scale the endpoint for delivery failure. Keep a test subscription without a filter during incidents if receiving a diagnostic copy is worth the extra traffic.
published message
        |
        v
SNS filter policy ── no match ──> FilteredOut
        |
     match
        v
endpoint delivery ── failure ──> retry / failure / DLQ
        |
      accepted
        v
consumer processing (may still fail)

Interview takeaway: I distinguish filtering from delivery by checking subscription-level filter metrics first, then delivery evidence and finally consumer processing, because an accepted delivery is not the same as successful business handling.

2. Why can SNS FIFO deduplicate messages that business logic considers different?

SNS FIFO deduplication is based on the configured deduplication ID, or on a hash of the message body when content-based deduplication is enabled—not on the business meaning of the event. Therefore two events that differ only in attributes, or in fields ignored by the producer's identity scheme, can be treated as the same message.

Common ways this happens include:

  • With content-based deduplication, SNS hashes the message body. Message attributes are not included in that content-based hash, so different attributes with identical bodies can collapse into one publication.
  • With explicit deduplication, reusing the same MessageDeduplicationId tells SNS that the messages are duplicates, even if their bodies differ.
  • Deduplication is a producer-side protection over a limited deduplication interval, not a durable business idempotency record. A retry outside that interval can be accepted again.
  • FIFO ordering is also scoped by MessageGroupId; it does not make separate business identities automatically distinct.

Choose the identity deliberately:

  1. Define what makes two events the same business operation: an order event ID, command ID, or another stable identifier. Do not derive it casually from a mutable payload.
  2. Set an explicit deduplication ID to that stable identity when retries of the same event must collapse. Ensure genuinely different events receive different IDs.
  3. Alternatively, include every business-distinguishing value in the message body and use content-based deduplication, but treat the body schema as part of the deduplication contract.
  4. Keep consumer-side idempotency as well. SNS FIFO reduces duplicate publication, but downstream retries, redeliveries, and database failures still require a durable uniqueness check.
business event ID:  order-8472 / status=PAID
SNS dedup ID:      event-9f2...

body:       {"orderId":"8472","status":"PAID"}
attributes: {"source":"billing"}  // not part of content hash

Interview takeaway: I make the deduplication identity explicit and stable, then retain consumer idempotency because SNS deduplication is not a substitute for a business-level uniqueness constraint.

3. How would you use SNS message attributes without breaking subscription filter policies?

Treat SNS message attributes as a versioned routing contract: publish the attribute with the exact name and SNS data type that the subscription policy expects. A filter policy normally evaluates message attributes, so putting the value only inside the JSON body will not satisfy it unless the subscription explicitly uses message-body filtering.

Important compatibility rules are:

  • Attribute names are case-sensitive, and a missing attribute does not match an ordinary equality condition.
  • A string value is not interchangeable with a number, and a scalar string is not interchangeable with a String.Array. Keep representations consistent across all publishers.
  • Filter policies can use operators such as anything-but, prefix, numeric, and exists, but each has type and value constraints. Test boundary cases rather than assuming a policy is self-explanatory.
  • If using body filtering, set the subscription's filter policy scope to MessageBody and publish valid JSON in the expected shape. Do not assume a body field is visible to a policy using the default attribute scope.
  • Changing a shared attribute's type can silently exclude old publishers or subscriptions. Roll out a new attribute name when compatibility matters.

A safe rollout looks like this:

  1. Define an attribute schema, including name, type, allowed values, and whether it is mandatory for routing.
  2. Publish a canary message containing the attributes and inspect the subscription filtering metrics for both matching and non-matching subscriptions.
  3. Update policies and publishers in a compatible order. During migration, publish both old and new attributes if the temporary duplication is acceptable.
  4. Use a diagnostic subscription with no filter to prove that the publisher emitted the expected attributes. Check the actual SNS publish request rather than only the domain object before serialization.
  5. Keep routing attributes small and stable; put detailed business data in the message body. Attributes are for selection, not for replacing the event schema.
{
  "eventType": ["OrderPaid"],
  "tenant": ["retail"]
}

// The publisher must send String attributes named exactly
// eventType and tenant; values in the JSON body alone do not match.

Interview takeaway: I use attributes as a deliberately versioned routing schema, matching names and SNS data types exactly, and choose body filtering explicitly when routing must inspect JSON.

4. A fanout suddenly slows down. How would you separate SNS throttling from subscriber backpressure?

Separate the two by looking at where latency and rejection begin: SNS throttling affects publishing or SNS's service-side delivery capacity, while subscriber backpressure shows an accepted fanout accumulating at a queue or endpoint. A healthy publish response does not mean every subscriber is keeping up.

Signals for SNS-side pressure include:

  • Publish calls returning throttling or quota errors, increased publisher latency, or failures across multiple topics and subscriptions at the same time.
  • A drop in accepted publish rate even though subscribers are healthy and their queues or endpoints remain empty.
  • SNS delivery metrics showing failures or delayed delivery for several subscriptions, rather than one slow consumer.
  • Quota, request-rate, message-size, or regional service-limit indicators that correlate with the incident.

Signals for subscriber backpressure include:

  • One subscription has growing SQS ApproximateNumberOfMessagesVisible or ApproximateAgeOfOldestMessage, while other subscriptions remain current.
  • Lambda consumers show throttles, high concurrent executions, errors, or increasing event age. HTTP endpoints show rising response time, timeouts, five-hundred-level responses, or connection failures.
  • SNS accepts publishes normally, but retries or a subscription dead-letter queue grow for the affected endpoint.

Diagnose and correct it as follows:

  1. Compare publisher request results and latency with SNS topic and per-subscription delivery metrics on the same timeline.
  2. Compare every subscription independently; fanout is not one shared consumer queue. Identify whether the problem follows the topic or one endpoint.
  3. For a slow consumer, scale workers or Lambda concurrency carefully, optimize processing, and set visibility and retry timeouts so work is not duplicated unnecessarily.
  4. For SNS throttling, reduce burstiness, use the documented retry and backoff behavior, and review the relevant service quotas. Do not hide a subscriber bottleneck by blindly increasing publisher retries.
publisher -> SNS accepted -> subscription A -> current
                         |
                         +-> subscription B -> SQS age rising
                                             -> consumer backpressure

Interview takeaway: I compare publish acceptance with each subscription's delivery and backlog metrics, then scale the constrained side instead of labeling every fanout delay an SNS throttle.

5. Why can changing SNS raw message delivery break consumers without changing business data?

Raw message delivery changes the transport envelope, not necessarily the business payload. A consumer that parses SNS's default JSON wrapper can therefore fail when the same event arrives as the bare message body, even though the domain fields and business meaning are unchanged.

With the default SNS-to-SQS or HTTP delivery, the consumer may receive an SNS envelope containing fields such as:

  • Type, MessageId, TopicArn, Subject, Timestamp, and the serialized Message.
  • SNS message attributes and, for some protocols, signature or subscription metadata used for validation.
  • A body that requires a second parsing step: first the SNS envelope, then the application message.

With raw delivery enabled:

  • The body is the original message, so code expecting Message can fail with a missing-field error or treat the whole event as malformed.
  • Metadata previously read from the envelope may disappear from the body. Consumers that use topic, message ID, subject, or timestamp must obtain equivalent metadata elsewhere or change their contract.
  • For SQS, SNS message attributes are delivered as SQS message attributes, but raw SQS delivery has a limit of ten message attributes; exceeding protocol limits can cause delivery problems.
  • Signature-validation or envelope-parsing code may no longer apply in the same way. Verify the protocol-specific security and authenticity design before changing the setting.

Make the change as a wire-contract migration:

  1. Inventory consumers and tests, including replay tools and dead-letter processors, and record whether each expects the envelope.
  2. Deploy a consumer that can recognize and handle the selected format, or create a parallel subscription and migrate consumers gradually.
  3. Test attributes, message IDs, malformed payloads, large messages, and dead-letter replay—not only the normal business JSON.
  4. Roll back by subscription if the new format breaks an old consumer. Treat raw delivery as a compatibility change even when the domain schema is untouched.
default body: {"Type":"Notification","Message":"{\"orderId\":8472}"}
raw body:     {"orderId":8472}

// The business event is equivalent; the wire contract is not.

Interview takeaway: Raw delivery is a transport-format change, so I migrate consumers and preserve required metadata explicitly even when the business payload stays identical.

Section 2: SQS Consumers

6. A queue's age rises while consumers look healthy. How do you locate the hidden bottleneck?

A rising ApproximateAgeOfOldestMessage with apparently healthy consumers usually means messages are being received but not deleted fast enough, or the real concurrency bottleneck is downstream of the poller. I trace the message from receive through business processing and deletion rather than treating invocation count as proof of throughput.

Look for these hidden constraints:

  • ApproximateNumberOfMessagesVisible rising means backlog is waiting to be received; ApproximateNumberOfMessagesNotVisible rising means work is in flight or stuck in visibility timeout.
  • Lambda reserved concurrency, account concurrency, event-source maximum concurrency, throttles, or a small container pool can cap actual parallelism.
  • Slow database connections, exhausted HTTP connection pools, lock contention, downstream throttling, and retries can make consumers look healthy while reducing delete rate.
  • A consumer can acknowledge logs before the actual DeleteMessage succeeds. Network errors, stale receipt handles, or process crashes then return messages to the queue.
  • A low receive count is not enough evidence: long polling, batch windows, filtering, and uneven message sizes can make invocation dashboards look normal.

Diagnose it in this order:

  1. Compare sent, received, deleted, visible, not-visible, and age metrics over the same interval. A widening gap between received and deleted points to processing or acknowledgment failure.
  2. Break down Lambda duration, throttles, errors, concurrency, batch size, and partial failures by event source. For self-managed consumers, measure poll latency, handler latency, delete latency, and active worker count.
  3. Trace representative messages through the database and downstream calls. Check connection-pool usage, lock waits, dependency latency, and retry volume.
  4. Fix the limiting stage: increase safe concurrency or batch size only after checking database capacity; remove unnecessary downstream retries; and make deletion happen only after durable business success.
visible + not_visible + deleted
        ↓
receive → handler → database/downstream → DeleteMessage
                              ↑
                 hidden capacity or latency limit

Do not blindly raise concurrency: it can move the bottleneck into the database and increase duplicate work when visibility timeouts expire. Queue age is also approximate, so use it as a trend and correlate it with the per-stage measurements.

Interview takeaway: I locate the first stage where throughput drops—from receive to durable completion to delete—then increase capacity only where the downstream system can safely absorb it.

7. How does SQS visibility timeout interact with Lambda timeout and partial batch failures?

Lambda receives an SQS batch and makes those messages invisible for the queue's visibility timeout; it deletes them only after the invocation reports success. The visibility timeout must cover the whole Lambda execution and batching delay, while partial batch responses determine whether successful messages are deleted when some records fail.

The important interactions are:

  • The visibility clock starts when SQS delivers the messages to Lambda, not when the handler begins processing each record.
  • If the function succeeds normally, Lambda acknowledges the batch. If it throws, times out, or the event source cannot obtain a valid response, the batch can become visible again and be retried.
  • With ReportBatchItemFailures enabled and the handler returning batchItemFailures, Lambda deletes successful records and retries only the listed failed records. A function-level exception still prevents useful partial reporting.
  • The visibility timeout should exceed the function timeout, and AWS recommends at least six times the function timeout for Lambda event source mappings, with additional allowance for batching windows and throttling.
public SQSBatchResponse handle(SQSEvent event) {
    List<SQSBatchResponse.BatchItemFailure> failed = new ArrayList<>();
    for (SQSEvent.SQSMessage message : event.getRecords()) {
        try {
            processIdempotently(message.getBody());
        } catch (RetryableException e) {
            failed.add(new SQSBatchResponse.BatchItemFailure(message.getMessageId()));
        }
    }
    return new SQSBatchResponse(failed);
}

Set and verify the relationship in production:

  1. Set the queue visibility timeout above the Lambda timeout plus batching and operational headroom; do not rely on a timeout that merely equals the function timeout.
  2. Configure the event source mapping for partial batch responses and return only genuinely retryable record identifiers.
  3. Keep record processing bounded so one slow item does not consume the entire visibility window. Make every record handler idempotent because retries remain possible.
  4. Alert on age, not-visible count, function timeouts, throttles, and batch-item failures together.

A longer timeout reduces premature retries but delays recovery from a crashed consumer and can keep poisoned records hidden longer. Partial batch failure improves throughput, but it requires correct response handling and does not remove the need for a DLQ.

Interview takeaway: I size visibility for the complete Lambda delivery-to-completion path, enable partial batch responses, and still design each record for safe replay.

8. Why can extending an SQS visibility timeout still produce duplicate processing?

Extending visibility prevents one common timeout race, but it cannot turn SQS into an exactly-once system. A duplicate can still result from a crashed worker, a lost delete, a stale receipt handle, a failed visibility extension, or SQS's at-least-once delivery behavior.

Typical failure paths include:

  • The worker finishes business work but crashes before DeleteMessage; the message becomes visible and another consumer processes it.
  • The worker extends visibility using an old receipt handle after the message has been received again. Receipt handles are tied to a particular receive, so the operation may not protect the current delivery.
  • A heartbeat request times out or loses connectivity. The consumer assumes the extension worked, but SQS does not share that assumption.
  • The visibility timeout expires just as the worker is deleting the message. Another consumer may receive it before the delete is accepted.
  • Even with a successful extension, standard SQS can deliver a message more than once. Extensions reduce premature redelivery; they do not provide a transaction spanning SQS and the database.
receive → process → durable commit → delete
     │                         │
     └─ heartbeat while slow ──┘

If the process or delete fails, replay is expected.
The business operation must tolerate that replay.

Make the outcome safe:

  1. Use a stable business operation key, often derived from the event ID or a domain idempotency key, and enforce uniqueness in the database.
  2. Commit the business change and its processed-event marker atomically when both belong in the same database.
  3. For long work, extend visibility with the current receipt handle and stop processing if the extension cannot be confirmed; do not extend indefinitely.
  4. Keep the handler retryable and configure a DLQ for poison messages. Monitor receive count, visibility-extension failures, and duplicate-key outcomes.

A database uniqueness constraint is stronger than an in-memory set, which disappears on restart and fails across multiple consumers. Idempotency may suppress a duplicate business effect while still allowing the message to be deleted after the original committed successfully.

Interview takeaway: Visibility extensions buy time, but only durable idempotency makes crashes, races, and at-least-once delivery safe.

9. A FIFO queue stops making progress. How would you identify the message-group head blocker?

A FIFO queue can appear stuck because one in-flight or repeatedly failing message is the head of a message group; later messages in that group cannot be delivered until the head is deleted or its visibility expires. I identify the group and message ID, then correlate its receive, failure, visibility, and delete history.

Useful signals are:

  • ApproximateNumberOfMessagesVisible can remain nonzero while a blocked group's later messages are withheld by FIFO ordering.
  • ApproximateNumberOfMessagesNotVisible and a high age for the oldest message indicate an in-flight head or a slow consumer, but queue metrics do not directly tell you which group is blocked.
  • The same message ID appearing repeatedly with an increasing receive count, no successful delete, and the same MessageGroupId is a strong poison-message pattern.
  • If Lambda is used, inspect function errors, timeouts, partial batch failures, and event-source concurrency. One group is serialized even when other groups have available parallelism.

Diagnose without disturbing the queue unnecessarily:

  1. Log MessageId, MessageGroupId, receive count, receive timestamp, processing outcome, and delete result for every delivery. Request the FIFO system attribute containing the group ID when receiving messages.
  2. Find groups with old deliveries, repeated failures, or a missing delete. Compare their processing latency with the visibility timeout.
  3. Inspect the head message's payload, downstream dependency, and idempotency record. A long-running message and a poison message need different fixes.
  4. After preserving evidence, fix the handler or quarantine the poison record through the supported DLQ/redrive process. If operationally necessary, allow visibility to expire rather than deleting a message whose business effect is unknown.
aws sqs receive-message \
  --queue-url "$QUEUE_URL" \
  --message-system-attribute-names MessageGroupId,ApproximateReceiveCount \
  --max-number-of-messages 10 \
  --visibility-timeout 30

Do not consume messages just to inspect them without a plan: receiving changes visibility and can create another misleading blocker. Increasing consumer concurrency helps only when there are multiple active groups; it cannot bypass ordering within one group.

Interview takeaway: For a FIFO stall, I find the oldest repeatedly undelivered message and its MessageGroupId, because that head—not general consumer concurrency—is usually the blocker.

10. How would you prevent a DLQ redrive from overwhelming the downstream database?

I treat a DLQ redrive as a new workload and throttle it independently of normal traffic. The safe target is the downstream database's spare capacity, not the queue's maximum delivery rate.

Controls should exist at more than one layer:

  • Use SQS redrive velocity, such as MaxNumberOfMessagesPerSecond on a message move task, and start with a small rate. Redrive in a canary batch before increasing it.
  • Cap consumer concurrency and batch size, or use a separate recovery consumer with its own reserved capacity. Leave headroom for live traffic.
  • Bound database connection pools and add a semaphore or token bucket around the expensive operation. This prevents a sudden redrive from creating unbounded application-side work.
  • Make processing idempotent. DLQ messages often failed before, so a replay can collide with data that was partially committed or already completed.
  • Watch database CPU, locks, connection usage, latency, error rate, queue age, and redrive receive counts. Stop or reduce redrive when the database shows saturation.
aws sqs start-message-move-task \
  --source-arn "$DLQ_ARN" \
  --destination-arn "$SOURCE_QUEUE_ARN" \
  --max-number-of-messages-per-second 10

A controlled run looks like this:

  1. Classify the DLQ first: fix schema, code, permissions, or dependency problems before replaying records.
  2. Pause or reduce the redrive if the error signature is still present; otherwise the messages simply return to the DLQ and add load.
  3. Redrive a small slice, observe successful durable completion and database headroom, then raise the rate gradually.
  4. Keep normal queue traffic and recovery traffic observable separately. For FIFO queues, preserve group ordering and avoid a recovery design that mixes related records in a way that violates the domain sequence.

Application throttling is still necessary because a redrive task rate limits movement, not necessarily the exact rate at which database work completes. The trade-off is recovery time: slower replay protects availability and makes failures easier to stop and diagnose.

Interview takeaway: I redrive gradually, cap recovery concurrency, and use database headroom and successful durable completion—not redrive speed—as the control signal.

Preparing for a full interview loop? Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)

Section 3: EventBridge Routing

11. EventBridge rules match some events but not others. How can you isolate the pattern mismatch?

I isolate an EventBridge pattern mismatch by first proving the exact event received, then testing that captured event against the pattern outside the rule. EventBridge matching is structural and exact in important places: source, detail-type, and nested detail fields must have the expected names, types, and values.

Common causes include:

  • The producer emits detail-type, while the pattern tests a differently named field or places it under detail.
  • A value is a string in the event but the pattern expects a number, or vice versa.
  • The pattern uses account or region values that differ from the actual event.
  • An operator such as prefix, anything-but, exists, or numeric matching is applied at the wrong nesting level.
  • The rule matches, but the target fails; this is a delivery problem rather than a pattern problem.

A practical production diagnosis is:

  1. Capture the complete event from producer logs, CloudTrail, an archive, or a temporary logging target. Do not reconstruct it from memory; omitted fields and JSON types matter.
  2. Run the exact event and pattern through aws events test-event-pattern. Check the command's region and account context, and validate JSON syntax separately.
  3. Inspect the rule's event bus, state, event pattern, and target configuration. Confirm the event was sent to that bus, not only to the default bus in another region.
  4. Check EventBridge metrics and target logs. A matching rule with target failures produces a different signal from a rule with zero matches.
  5. Reduce the pattern to source and detail-type, test it, then add nested constraints one at a time.
aws events test-event-pattern \
  --event-pattern file://pattern.json \
  --event file://event.json

For a temporary investigation, a broad rule targeting a log-ingestion Lambda can show the real envelope, but remove or narrow it afterward. Broadening the permanent rule merely to make events arrive can silently route unrelated events, so the safer fix is to correct the producer contract or pattern and add contract tests around representative event fixtures.

Interview takeaway: I separate matching from delivery, test the exact JSON with test-event-pattern, and tighten the final pattern only after verifying the real event envelope.

12. Why can EventBridge archive replay create duplicates in a state-changing consumer?

An EventBridge archive replay can create duplicates because replay publishes events again; it does not rewind the consumer's database or restore its previous state. The replayed event may therefore be processed alongside the original delivery, and EventBridge does not make a state-changing consumer idempotent for you.

Duplicates can arise when:

  • The original event was delivered successfully but the consumer timed out before recording completion.
  • A replay overlaps with live traffic for the same time range.
  • A rule or target changed, so the replay reaches a consumer that did not receive the original event.
  • The consumer performs the business write and crashes before recording the event ID, or records the ID before the business transaction commits.
  • Retries, redrives, or multiple matching rules deliver semantically equivalent events through different paths.

Before replaying, I would:

  1. Identify the event's stable identity. Prefer a producer-assigned event ID or business command ID; do not use the delivery timestamp as an identity.
  2. Define whether the operation is naturally idempotent, such as setting status to SHIPPED, or needs deduplication, such as adding a ledger entry.
  3. Put the idempotency key and the state change in one database transaction, using a unique constraint or conditional update. A separate cache check is not sufficient under concurrency.
  4. Replay into an isolated bus or rule when validating behavior, and use a narrow time window. Monitor the replay and live consumer independently.
  5. Reconcile affected entities after replay; a deduplication table prevents repeated effects but does not repair a previously partial side effect.
create table processed_event (
  consumer_name varchar(100) not null,
  event_id varchar(200) not null,
  processed_at timestamp not null,
  primary key (consumer_name, event_id)
);

For external effects such as payments or emails, the database transaction cannot atomically include the provider. Use an outbox or provider idempotency key as well. This adds storage and reconciliation work, but it is safer than assuming archive replay is a once-only operation.

Interview takeaway: I treat replay as a new delivery and make every state-changing effect idempotent using a stable event or business key.

13. How would you configure an EventBridge retry policy and DLQ without masking the original error?

I configure retries as a bounded recovery window and an SQS DLQ as an operational handoff, while preserving the event and failure metadata needed to diagnose the first failure. The consumer must still log the original exception and correlation data; EventBridge's DLQ is not a substitute for application logs or tracing.

The important decisions are:

  • MaximumRetryAttempts controls retry count, from 0 through 185; MaximumEventAgeInSeconds limits the total event age, from 60 through 86400 seconds.
  • The rule's target has a retry policy, while the DLQ is configured on that target. These settings do not make a non-idempotent consumer safe.
  • EventBridge retries delivery failures such as target errors, throttling, or unreachable targets. A successful HTTP response or Lambda completion stops EventBridge retries, even if the application accepted the event and failed asynchronously later.
  • The SQS DLQ message retains the original event body and attributes such as ERROR_CODE, ERROR_MESSAGE, EXHAUSTED_RETRY_CONDITION, RULE_ARN, and TARGET_ARN.

A safe setup and diagnosis is:

  1. Choose an age and attempt limit based on dependency recovery time, then configure both rather than allowing an unbounded operational delay.
  2. Grant EventBridge permission to send to the DLQ, and if the queue uses a customer managed KMS key, grant the required KMS permissions too.
  3. Give the consumer a correlation ID and log the event ID, attempt context, exception class, and dependency response before returning failure.
  4. Alert on the rule's failed-invocation metrics and DLQ depth. Inspect the DLQ attributes to distinguish timeout, throttling, permission, and exhausted-retry cases.
  5. Fix the consumer before redriving. Make processing idempotent, then redrive deliberately and record which events were retried.
{
  "RetryPolicy": {
    "MaximumEventAgeInSeconds": 3600,
    "MaximumRetryAttempts": 8
  },
  "DeadLetterConfig": {
    "Arn": "arn:aws:sqs:us-east-1:123456789012:orders-events-dlq"
  }
}

Short limits reduce duplicate exposure but increase DLQ traffic during a transient outage; longer limits improve eventual delivery but can delay recovery and replay stale events. The correct balance depends on event validity windows and whether the consumer can safely repeat work.

Interview takeaway: I bound retries, preserve the original event plus EventBridge failure attributes in an SQS DLQ, and fix observability and idempotency rather than hiding errors behind redelivery.

14. A cross-account event never arrives. How would you verify the bus policy and target role?

For a cross-account event bus target, I verify both sides: the destination bus resource policy must allow the source account to call events:PutEvents, and the source rule's target role must also be allowed to put events to that exact destination bus ARN. A valid policy in only one account is not enough.

The usual failure points are:

  • The rule targets the wrong account, region, bus name, or bus ARN.
  • The destination bus policy names the wrong source account, organization condition, or principal.
  • The source rule has no role, or its role policy grants events:PutEvents on a different bus ARN.
  • The role trust policy does not trust events.amazonaws.com, so EventBridge cannot assume it.
  • The event was sent to the source account's default bus, while the rule exists on a custom bus, or the rule is disabled.
  • The event arrives at the destination bus but no destination rule matches it.

I would verify it in this order:

  1. Describe the source rule and inspect its target, role ARN, and event bus. Confirm the destination ARN character for character and check both regions.
  2. Inspect the destination bus policy with aws events describe-event-bus. Confirm its Principal and any aws:PrincipalOrgID or account conditions.
  3. Inspect the role trust policy and identity policy. The role needs a trust relationship for EventBridge and events:PutEvents on the destination bus.
  4. Use CloudTrail data or management events, EventBridge invocation metrics, and destination-bus metrics to locate the boundary where delivery stops.
  5. Send a deliberately tagged test event, then check the destination bus and its matching rule separately.
aws events describe-event-bus \
  --name central-bus \
  --region us-east-1

aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::111122223333:role/EventBridgeCrossAccountRole \
  --action-names events:PutEvents \
  --resource-arns arn:aws:events:us-east-1:444455556666:event-bus/central-bus

Keep the destination policy narrow: allow only the required source account or organization and, where appropriate, constrain the event bus resource. If the bus policy is correct but the destination rule does not match, the cross-account transport worked; debug the destination pattern instead of changing IAM.

Interview takeaway: I prove cross-account delivery at each boundary: source target ARN, assumable target role, destination bus policy, then destination-rule matching.

15. Why can EventBridge ordering assumptions fail even when events share a detail key?

EventBridge does not provide ordering merely because events contain the same detail key. Events can be accepted, matched, retried, and delivered independently, often concurrently, and different rules or targets create additional paths with no shared sequence for that key.

Ordering assumptions fail because:

  • EventBridge is a distributed event router, not a per-key ordered log.
  • Network timing and parallel target invocation can deliver a later update before an earlier one.
  • A failed event is retried while a later event succeeds, so the retry can arrive out of order.
  • Archive replay and DLQ redrive introduce another delivery time, unrelated to the original event time.
  • Two producers can emit the same business key from different processes or regions without a single sequence authority.
  • An event's time field describes publication time, not a guaranteed processing order.

For stateful consumers, I would:

  1. Define an ordering field at the producer, such as a per-aggregate version or monotonic sequence. A timestamp alone is usually insufficient because clocks and ties are problematic.
  2. Persist the last accepted version and apply updates conditionally, rejecting or parking stale versions. Make the decision and state update one transaction.
  3. If strict per-key order is a hard requirement, route through an ordering-capable design, such as a partitioned stream keyed by aggregate ID, or a FIFO queue with consistent message-group assignment where supported by the chosen integration.
  4. Make the consumer idempotent as well as ordered; ordered delivery can still be retried.
  5. Monitor gaps and stale-version rejections, and provide reconciliation when a missing predecessor later arrives.
update account
set status = ?, version = ?
where account_id = ?
  and version < ?;

This conditional update protects against an older event overwriting newer state, but it does not automatically recover a missing version. For workflows where every transition matters, store the event or command in an append-only record and process it through a component that owns sequencing, rather than relying on EventBridge delivery order.

Interview takeaway: I never infer ordering from a shared detail key; I use explicit per-aggregate versions and conditional writes, or an ordering-capable intermediary when sequence is mandatory.

Section 4: Lambda Reliability

16. A Lambda invocation runs twice after a timeout. How should the handler make its side effect safe?

Treat a timeout as an unknown result, not as a failed operation: the handler must use a stable idempotency key and make the side effect conditional on that key. The protection must be durable and shared across invocations, because a local variable or in-memory lock disappears when Lambda retries on another execution environment.

A timeout can occur after the payment, email, database update, or HTTP request has already completed but before Lambda reports success. The retry therefore cannot know whether it is repeating work. The strongest design makes the business write and its idempotency record part of one database transaction, or calls a downstream API that accepts the same idempotency key and deduplicates it.

Useful signals and design choices include:

  • Repeated request IDs or business keys in logs, with different Lambda request IDs.
  • A durable table with a unique key and states such as IN_PROGRESS and COMPLETED; conditional writes prevent concurrent claims.
  • A transactional outbox when the database change must reliably publish a message after commit.
  • A sufficiently long retention period for the idempotency record, based on the maximum retry and redelivery window.
// Conceptual transaction
BEGIN;
INSERT INTO idempotency(key, status)
  VALUES (:key, 'COMPLETED')
  ON CONFLICT (key) DO NOTHING;
-- Only the transaction that inserted the key performs the business update.
COMMIT;

Diagnose by correlating the stable key, Lambda request IDs, timeout duration, downstream operation IDs, and database audit records. A conditional claim alone is not enough if the external side effect happens after the claim and the process times out: the retry may see an unfinished record or the external call may still be duplicated. Use an atomic downstream operation, an outbox, or a reconciliation process for that gap. The trade-off is extra storage and state-management complexity, plus careful handling of stuck IN_PROGRESS records.

The safest handler is therefore idempotent at the business boundary, not merely protected against duplicate Java method calls.

Interview takeaway: I would assume every timeout may have committed and use a durable, stable key with an atomic or independently idempotent side effect.

17. Why can Lambda asynchronous retries amplify an outage, and how do destinations change recovery?

Asynchronous Lambda invocation can turn one dependency failure into a growing retry stream: Lambda retains the event, retries failures, and may process more events concurrently while the dependency is still unavailable. Destinations do not remove retries; they provide an explicit success or failure handoff after processing, so exhausted events can be routed for inspection and controlled replay.

For asynchronous invocation, function errors normally cause retries, with the event eventually discarded or sent to a configured dead-letter queue or failure destination. Throttling and some service-side errors can also be retried, subject to Lambda's event age and retry behavior. During an outage, each retry consumes concurrency, increases downstream load, and competes with fresh events. A function that times out while calling a slow dependency is especially prone to this amplification.

Look for these production signals:

  • Lambda Errors, Throttles, duration, and concurrent executions rising together.
  • Async event age increasing and a growing destination or DLQ count.
  • Downstream timeout, rate-limit, or connection-pool errors correlated with Lambda retry bursts.
  • The same event ID appearing with multiple Lambda request IDs.

A practical recovery path is:

  1. Set an appropriate maximum event age and retry policy, and fail quickly when the dependency is known to be unhealthy.
  2. Configure an on-failure destination such as SQS, SNS, or EventBridge, or a DLQ, so exhausted events are durable and observable.
  3. Give the destination consumer a controlled replay mechanism with idempotency and rate limiting; do not immediately redrive everything into the outage.
  4. Use an on-success destination when processing must emit an audit or workflow event, remembering that it is not a transactional replacement for an outbox.

Destinations receive invocation records containing the original event and execution result, which is useful for diagnosis and replay. They are asynchronous-invocation features; an SQS event source mapping has different redelivery and DLQ mechanics. The trade-off is delayed recovery and operational storage: lowering retries protects the dependency but requires a deliberate replay process and alerting.

Interview takeaway: I would cap retry pressure, route exhausted events to a durable destination, and replay them at a controlled rate after the dependency recovers.

18. How would you combine reserved concurrency with SQS batch settings to contain a failing consumer?

Use the SQS event source mapping's MaximumConcurrency to limit this consumer and Lambda reserved concurrency to enforce the account-level ceiling; keep the reserved value at or above the mapping limit. Then tune batch size and visibility timeout so a failing batch cannot tie up excessive work or become visible while it is still being processed.

Reserved concurrency limits the total simultaneous executions of the function, including invocations from other event sources. For SQS, MaximumConcurrency limits how far that particular mapping scales. If reserved concurrency is lower than the mapping maximum, Lambda is throttled and messages remain in flight or are redelivered. That can contain load, but it is usually a configuration mistake rather than a useful steady state.

For a failing consumer, consider:

  • Lower MaximumConcurrency to protect the downstream system and limit the number of failing batches.
  • Set reserved concurrency to a deliberate ceiling, leaving capacity for unrelated functions or mappings.
  • Reduce BatchSize when one poison message causes expensive whole-batch retries; use partial batch responses when possible.
  • Set SQS visibility timeout to at least six times the function timeout, plus any batching window, and configure a redrive policy for poison messages.
Resources:
  Consumer:
    Type: AWS::Lambda::EventSourceMapping
    Properties:
      FunctionName: !Ref Function
      EventSourceArn: !Ref Queue
      BatchSize: 10
      ScalingConfig:
        MaximumConcurrency: 5
      FunctionResponseTypes:
        - ReportBatchItemFailures

# Separately set the function's ReservedConcurrentExecutions
# to a value >= 5 and compatible with all its event sources.

Diagnose before changing limits:

  1. Compare ApproximateAgeOfOldestMessage, receive counts, Lambda throttles, errors, duration, and concurrent executions.
  2. Check whether other event sources share the function's reserved concurrency.
  3. Quarantine poison messages through the queue redrive policy, then raise concurrency gradually after the dependency is healthy.

The trade-off is throughput: a smaller batch or concurrency limit increases backlog and latency, while a larger value improves drain speed but can overwhelm the dependency and multiply retries.

Interview takeaway: I would cap this mapping explicitly, reserve enough capacity for that cap, and combine small enough batches with partial failure handling and a poison-message redrive policy.

19. A partial batch failure keeps replaying successful records. How do you configure the response?

Configure the SQS event source mapping with ReportBatchItemFailures, and have the handler return the identifiers of only the records that failed. Lambda then deletes successful records and makes only those failed records eligible for another delivery; if the handler throws instead of returning a valid partial response, the whole batch is treated as failed.

The response must use each failed SQS record's messageId as itemIdentifier. The handler should catch per-record exceptions, record the failure, and continue with independent records. If processing order matters, especially for an SQS FIFO queue, stop at the first failure and report that record plus every unprocessed record after it. Otherwise later records may be processed out of order relative to the failed one.

// Response shape returned by the Java handler
{
  "batchItemFailures": [
    { "itemIdentifier": "message-id-that-failed" }
  ]
}

// Event source mapping configuration
FunctionResponseTypes:
  - ReportBatchItemFailures

Implement and verify it in this order:

  1. Enable ReportBatchItemFailures on the event source mapping, not merely in application code.
  2. Process each record with an idempotent operation and add its messageId only when processing fails.
  3. Return a successful response for a batch with no failures; do not throw after building a partial result.
  4. Test a batch containing one permanent failure and several successful records, then confirm the queue's receive counts and logs show only the failed record replaying.

Common causes of apparent replay are:

  • The mapping was not updated, or the wrong mapping UUID was changed.
  • The handler threw, timed out, or returned malformed JSON, causing whole-batch retry.
  • The failed record is retried correctly but the successful business operation is not idempotent.
  • The visibility timeout expires before processing finishes, allowing duplicate delivery.

Partial failure reduces duplicate work but does not provide exactly-once delivery. Records can still be delivered more than once, so the side effect for every message must remain idempotent and poison messages need a redrive policy.

Interview takeaway: I would enable partial batch responses, return only failed message IDs, and still make every record's side effect idempotent.

20. Why can an idempotency key based only on request time fail under Lambda retries?

A timestamp alone is not an identity: it can change between attempts, collide for legitimate requests, or be generated by different clocks. An idempotency key must be stable across the entire retry chain and unique for the intended business operation, usually by propagating an event ID or client-supplied key into a durable deduplication store.

If the key is created inside the Lambda handler from the current time, a retry after a timeout generates a new key and repeats the side effect. If it is taken from a producer timestamp, a producer retry may create a new event timestamp even though it represents the same operation. Conversely, two valid requests arriving in the same time unit can receive the same key. Clock skew, timestamp precision, serialization differences, and expiration of old records create further failure modes.

Prefer, in order:

  • A stable producer-generated event ID carried unchanged through retries.
  • A client idempotency key tied to a defined business operation, such as an order creation request.
  • A deterministic key derived from a canonical business identifier and operation type.
  • A canonical payload hash only when identical payloads are guaranteed to mean the same operation; otherwise distinct requests may be incorrectly merged.
String key = event.getId(); // supplied by the event, not generated at retry time
PutItemRequest request = PutItemRequest.builder()
    .tableName("Idempotency")
    .item(Map.of("id", AttributeValue.fromS(key)))
    .conditionExpression("attribute_not_exists(id)")
    .build();

Validate the scheme by:

  1. Logging the key, event ID, producer attempt, and Lambda request ID without using the request ID as the business identity.
  2. Replaying the exact event and confirming the same key is observed.
  3. Testing two concurrent legitimate requests and a retry created after a timeout.
  4. Retaining the key for longer than the maximum redelivery and replay window, with a policy for completed, failed, and in-progress states.

The conditional write prevents two workers from claiming the same operation, but it does not by itself make an external call atomic. Pair it with an idempotent downstream API, a transaction, or an outbox and reconciliation design. A timestamp can be useful metadata; it should not be the deduplication identity.

Interview takeaway: I would propagate a stable operation ID from the event or client and enforce it with a durable conditional record, never derive identity from the retry's current time.

Key Takeaways

  • Treat SNS filter evaluation, delivery status, and endpoint health as separate parts of the investigation.
  • Message deduplication is based on the configured FIFO identity and content rules, not on whether the business considers two events equivalent.
  • Use stable, consistently typed SNS message attributes when subscription filter policies determine delivery.
  • Separate producer throttling from subscriber backpressure by comparing service metrics, delivery latency, queue depth, and consumer capacity.
  • A rising SQS age metric requires investigation of concurrency, message-group serialization, visibility timeouts, downstream dependencies, and poison messages.
  • Coordinate SQS visibility timeout with Lambda timeout, batch behavior, and partial failure reporting so unfinished records can return without replaying completed work unnecessarily.
  • EventBridge debugging starts with the event envelope, pattern semantics, bus permissions, target permissions, and target delivery metrics.
  • Archive replay and asynchronous retries are normal duplicate-delivery paths, so state-changing consumers need durable idempotency.
  • Use reserved concurrency and SQS batch controls together to limit pressure on a failing dependency without creating an avoidable queue backlog.
  • A reliable idempotency key represents the business operation or event identity, not merely the time at which a Lambda invocation occurred.

Frequently Asked Questions

Should every AWS event consumer use a database idempotency table?

Not necessarily. The right mechanism depends on the side effect and its storage system. A conditional write, unique constraint, compare-and-set update, or provider-native deduplication may be sufficient. A database idempotency record is useful when the operation spans retries and the target cannot enforce uniqueness itself. The record should retain enough state to distinguish completed, in-progress, and failed attempts safely.

How can I tell whether a retry is safe?

Identify every external effect first, including database writes, emails, calls to payment or inventory systems, and emitted events. A retry is safe when repeating the operation produces the same intended state or when the target accepts a stable idempotency key. If neither is true, add a durable operation record, use conditional updates, or redesign the workflow before increasing retry attempts.

When should a message be moved to a DLQ?

A DLQ is appropriate when repeated delivery cannot complete because of a poison message, a persistent validation problem, or an unavailable dependency that should not block normal processing indefinitely. It is not a substitute for monitoring. Record the original context and failure reason, alert on arrival, and define a controlled repair or redrive process that respects downstream capacity.

What should be logged for distributed message troubleshooting?

Log the event or message identifier, source, subject or type, correlation identifier, delivery attempt where available, queue or bus context, consumer version, and the outcome. Avoid logging secrets or full sensitive payloads. Structured logs should make it possible to compare producer, service, and downstream timestamps while preserving enough context to explain filtering, retries, duplicates, and failures.

How do replay and redrive differ operationally?

A replay usually re-emits stored events from an archive or another retained source, while a redrive returns failed messages from a DLQ to a source queue or processing path. Both can create duplicates, but their controls differ. Validate the destination, throttle the operation, monitor downstream saturation, and ensure consumers can recognize already-applied business operations.

Conclusion

Reliable AWS messaging is less about choosing one delivery guarantee and more about designing for the gaps between services. SNS filters, SQS visibility, EventBridge routing, Lambda retries, and DLQ workflows each expose different failure boundaries. Senior-level reasoning connects those boundaries to metrics, permissions, payload identity, concurrency, and durable state. If consumers make side effects idempotent and operators can trace a message from publication through recovery, duplicates and retries become controlled operational cases rather than production surprises.

Which question would you find the hardest? Tell me in the comments.

Explore More Java Interview Resources

Cloud, DevOps & System Design for Java Backend (200 Qs: Docker, Kubernetes, AWS, CI/CD, Terraform, databases, system design)
https://topmate.io/logicbrace/2294488

Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
https://topmate.io/logicbrace/2294498

Complete Java Full Stack Developer Kit (900 Qs: Core Java, Spring Boot & Microservices, Cloud/DevOps/System Design, React & Angular)
https://topmate.io/logicbrace/2306382

AWS – 20 Production Scenarios Every Senior Developer Should Know (with Answers)

Post a Comment

0 Comments

Close Menu