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 guideFirst 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:
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.NumberOfNotificationsFailed, endpoint delivery-status logs, HTTP response or timeout logs, Lambda invocation errors, or an SQS dead-letter queue, depending on the protocol.In production, investigate in this order:
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.
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:
MessageDeduplicationId tells SNS that the messages are duplicates, even if their bodies differ.MessageGroupId; it does not make separate business identities automatically distinct.Choose the identity deliberately:
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.
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:
String.Array. Keep representations consistent across all publishers.anything-but, prefix, numeric, and exists, but each has type and value constraints. Test boundary cases rather than assuming a policy is self-explanatory.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.A safe rollout looks like this:
{
"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.
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:
Signals for subscriber backpressure include:
ApproximateNumberOfMessagesVisible or ApproximateAgeOfOldestMessage, while other subscriptions remain current.Diagnose and correct it as follows:
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.
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.With raw delivery enabled:
Message can fail with a missing-field error or treat the whole event as malformed.Make the change as a wire-contract migration:
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.
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.DeleteMessage succeeds. Network errors, stale receipt handles, or process crashes then return messages to the queue.Diagnose it in this order:
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.
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:
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.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:
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.
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:
DeleteMessage; the message becomes visible and another consumer processes it.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:
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.
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.MessageGroupId is a strong poison-message pattern.Diagnose without disturbing the queue unnecessarily:
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.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.
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:
MaxNumberOfMessagesPerSecond on a message move task, and start with a small rate. Redrive in a canary batch before increasing it.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:
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)
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:
detail-type, while the pattern tests a differently named field or places it under detail.account or region values that differ from the actual event.prefix, anything-but, exists, or numeric matching is applied at the wrong nesting level.A practical production diagnosis is:
aws events test-event-pattern. Check the command's region and account context, and validate JSON syntax separately.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.
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:
Before replaying, I would:
SHIPPED, or needs deduplication, such as adding a ledger entry.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.
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.ERROR_CODE, ERROR_MESSAGE, EXHAUSTED_RETRY_CONDITION, RULE_ARN, and TARGET_ARN.A safe setup and diagnosis is:
{
"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.
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:
events:PutEvents on a different bus ARN.events.amazonaws.com, so EventBridge cannot assume it.I would verify it in this order:
aws events describe-event-bus. Confirm its Principal and any aws:PrincipalOrgID or account conditions.events:PutEvents on the destination bus.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.
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:
time field describes publication time, not a guaranteed processing order.For stateful consumers, I would:
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.
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:
IN_PROGRESS and COMPLETED; conditional writes prevent concurrent claims.// 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.
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:
Errors, Throttles, duration, and concurrent executions rising together.A practical recovery path is:
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.
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:
MaximumConcurrency to protect the downstream system and limit the number of failing batches.BatchSize when one poison message causes expensive whole-batch retries; use partial batch responses when possible.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:
ApproximateAgeOfOldestMessage, receive counts, Lambda throttles, errors, duration, and concurrent executions.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.
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:
ReportBatchItemFailures on the event source mapping, not merely in application code.messageId only when processing fails.Common causes of apparent replay are:
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.
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:
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:
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.
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.
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.
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.
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.
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.
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.
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

0 Comments