FastAPI / Advanced: lifecycle and reliable service design / Lesson 21
Webhook verification and replay-safe processing
Verify a provider’s signed request and persist a stable event identity before processing retryable webhook deliveries.
On this page
Lesson goals
- Identify raw-body signature and replay boundaries.
- Distinguish authentication from event deduplication.
- Test duplicate, stale and tampered deliveries.
- Verify provider-defined raw bytes and distinguish signature authenticity from replay protection.
- Design atomic receipt deduplication and recoverable processing with safe operational tests.
Read the provider contract
A webhook is an inbound request initiated by another system. The exact signature format, timestamp rules, retry policy and event identifier are provider-specific; follow that provider’s documented contract rather than assuming all webhooks use the same HMAC format. Bound request size and handling time at the appropriate server and application layers. Treat headers and body as untrusted until verification succeeds, and keep signing secrets outside source code and logs.
Verify the exact signed bytes
Many protocols sign the original bytes, so parsing and reserializing JSON before checking a signature can change the signed representation. The illustrative helper compares an HMAC-SHA256 hexadecimal digest using compare_digest. It is a synthetic protocol example, not a complete provider verifier: obtain the key securely, validate the specified signature format, include any timestamp or prefix required by the real provider, and reject a mismatch before processing.
import hashlib
import hmac
def valid_signature(secret: bytes, body: bytes, supplied: str) -> bool:
if len(supplied) != 64 or any(c not in "0123456789abcdef" for c in supplied):
return False
expected = hmac.new(secret, body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, supplied)
This helper illustrates constant-time comparison for a simple hex-digest protocol. It omits provider-specific timestamp, key rotation and encoding rules.
Separate signature and deduplication
A valid signature shows that the message matches the shared-key check under the chosen protocol; it does not prevent the same valid message from being replayed. Validate the provider’s timestamp tolerance when supplied, then use its stable event identifier and a database uniqueness constraint to record accepted work. Associate the marker with the intended state change transactionally. External effects need their own idempotency or reconciliation because they do not share that database transaction.
Keep the HTTP boundary narrow
The handler sketch reads raw body bytes and rejects a failed verification before parsing. Its verifier and processing functions are application-specific; it does not implement a provider’s authentication scheme. After verification, validate the event schema and type, persist the event identity and processing intent, and return the status required by the provider contract. Acknowledge only after the durability boundary the system actually promises, and keep lengthy work in an appropriate durable worker.
from fastapi import HTTPException, Request
async def receive(request: Request):
body = await request.body()
signature = request.headers.get('x-signature', '')
if not verify_provider(body, signature):
raise HTTPException(status_code=401, detail='Invalid signature')
await accept_event(body)
return {'accepted': True}
verify_provider and accept_event must implement the real provider contract and durable processing policy. The fragment is not a complete webhook.
Test failure and recovery
Using synthetic payloads and keys, test a valid delivery, one changed byte, a missing or malformed signature, a stale timestamp and the same event twice. Assert both response and durable state, including the absence of an effect after rejection. Simulate failure after acceptance and during retry. A local request test demonstrates the handler’s contract; it does not prove the provider, proxy size limits or worker system behave as configured in production.
Verify the provider-defined bytes first
A webhook is an inbound request whose sender claims to be a provider. Treat its headers and body as untrusted until the configured verification procedure succeeds. If the provider signs the raw body, read the exact bytes delivered to the application and compute the expected signature over those bytes using the provider’s documented algorithm, secret, prefix, and header format. Parsing JSON and serializing it again can alter whitespace, key order, or encoding, producing different bytes even when the apparent data is equivalent. Verify before applying business effects, then parse and validate the event schema.
For an HMAC-based example, Python’s hmac module can calculate a digest and compare_digest can compare a supplied digest with the expected value in a way intended to reduce timing leakage. Header parsing, allowed algorithms, timestamp construction, and key selection must follow the actual provider specification; do not copy a fictional signing format into production. A signature authenticates the signed material under the key assumptions, not every unsigned header or the correctness of the provider’s business data.
Separate authenticity from freshness and replay
A valid signature can accompany the same event more than once. Some providers include a timestamp in the signed material and define an acceptable tolerance; verify the timestamp and the signature exactly as that provider specifies, with a controlled clock and an explicit skew policy. A timestamp that is not covered by the signature can be altered and is not sufficient replay protection. A freshness window also does not prevent duplicates delivered within that window, so stable event identity and durable deduplication remain necessary.
Store the provider’s stable event or delivery identifier in an appropriately scoped durable record after successful verification. Define whether the identifier is global to the provider, account, endpoint, or tenant according to the provider contract. The unique constraint must match that scope. Verify each incoming request before treating its identifier as trusted, and avoid marking an invalid request as accepted merely because it claims an existing event ID. Do not confuse legitimate provider retries with an attacker replay; handle both safely under the documented response policy.
Commit acceptance and effects consistently
A common design verifies the request, validates the event, and inserts a unique receipt plus a durable processing intent in one local transaction. If the transaction fails, do not acknowledge durable acceptance as though the event were saved. If it commits but the response is lost, the provider may retry; the next verified request should recognize the same receipt and return a provider-compatible response without repeating the effect. A background callback alone is not durable processing.
Concurrent duplicates can both pass an application-level existence check before either inserts. A database unique constraint or equivalent atomic mechanism must arbitrate the receipt identity. For a local transactional effect, the receipt and effect can share a transaction; for deferred work, persist an outbox or job intent and make the worker idempotent. An external effect requires the provider’s supported idempotency mechanism or reconciliation, because a local receipt cannot automatically roll back a remote action. Define handling for an existing event ID paired with different signed content rather than silently conflating them.
Bound input, secrets, and failure handling
Enforce request-body limits at appropriate transport and application boundaries so signature verification does not require unbounded memory or work. Check the provider’s maximum payload and retry contract, and design for expected traffic spikes. Keep signing secrets out of source code, responses, and logs. Plan rotation with the provider’s supported key identifiers or an explicit overlap period; test old and new keys and eventual retirement without accepting an unbounded list of stale secrets. Use synthetic secrets in examples and isolated tests only.
Return only safe error categories for malformed headers, invalid signatures, expired signed timestamps, or invalid event schemas. Do not log raw payloads or signature material by default. Decide which failures should receive a retryable response under the provider’s protocol and which are permanent, then monitor signature failures, duplicate counts, processing backlog, and reconciliation without high-cardinality secrets or protected payloads. Rate limiting and network controls complement signature verification; they do not replace it.
Test byte fidelity, races, and recovery
Build fixtures with known raw byte sequences, a synthetic secret, and expected signatures derived according to the selected provider’s specification. Test a valid request, one-byte body change, wrong secret, missing or malformed signature, encoding differences, and boundary timestamps if the provider signs a timestamp. Verify that an invalid signature cannot create a receipt or business effect. Test sequential duplicates and concurrent duplicate insertion against an isolated database with the actual uniqueness constraint.
Force failure before receipt commit, a lost acknowledgement after commit, and a worker crash after an external send but before completion is recorded. Assert durable receipt and effect counts, provider-compatible responses, and safe logs. A TestClient fixture with a fake store proves local routing and decisions, not provider connectivity, production proxy body preservation, database race behavior, or external delivery. Use separate authorized isolated integration tests for those boundaries. The examples below are illustrative and use a fictional HMAC protocol unless explicitly identified otherwise; they are not qualified production webhook implementations.
20 worked examples
1. Read raw request bytes
Problem: Capture the body before parsing its JSON.
- The request object supplies the received body bytes.
- The application can pass those bytes to its provider-specific verifier before parsing.
@app.post("/webhook")
async def webhook(request: Request):
raw = await request.body()
# verify provider signature over raw before parsing
return {"bytes": len(raw)}
# illustrative fixture; verifier omitted
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The fixture captures the exact body bytes available to the app.
Why this result follows: Raw-byte verification preserves the provider-defined signed representation.
2. Synthetic HMAC comparison
Problem: Compare a calculated digest with a synthetic header.
- The expected digest is calculated from the synthetic secret and raw bytes.
- The constant-time comparison helper checks the matching synthetic digest.
secret = b"test-secret"
raw = b'{"id":"evt-1"}'
expected = hmac.new(secret, raw, hashlib.sha256).hexdigest()
supplied = expected # synthetic matching fixture
assert hmac.compare_digest(expected, supplied)
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The assertion succeeds for this controlled match.
Why this result follows: The comparison checks the digest over the unchanged signed bytes.
3. One-byte change
Problem: Reject a body altered after signing.
- The received bytes differ from the bytes used to create the signature.
- Recomputing the HMAC over the received body produces a different digest in this fixture.
signed body: b'{"id":"evt-2"}'
received body: b'{"id":"evt-3"}'
secret: same synthetic key
expected signature for signed body != digest for received body
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The signature comparison fails and no event is accepted.
Why this result follows: A keyed digest binds the signature to the signed bytes.
4. Whitespace changes bytes
Problem: Explain equivalent JSON with a different signature.
- The second representation adds a space after the colon.
- A raw-body signature is computed over bytes, not semantic JSON equivalence.
signed: b'{"id":1}'
reserialized: b'{"id": 1}'
parsed objects: equivalent
byte sequences: different
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: Verification against the reserialized bytes can fail.
Why this result follows: Parsing and serialization can change the signed representation.
5. Wrong synthetic secret
Problem: Reject a digest made with another key.
- The receiver computes its expected digest with a different synthetic key.
- The provided digest was created using the sender’s key.
sender key: b"test-A"
receiver key: b"test-B"
body: b"event"
signature comparison: fails
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The verifier rejects the request in this fixture.
Why this result follows: HMAC verification requires the matching secret key.
6. Missing signature header
Problem: Reject a request before processing its body.
- The required authentication material is not supplied.
- The endpoint follows its documented rejection path before accepting an event.
signature header: absent
policy: require provider signature
receipt insertions: 0
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: No receipt or business effect is created.
Why this result follows: A missing required signature cannot establish authenticity.
7. Provider-specific header
Problem: Recognize a documented GitHub signing format.
- GitHub documents the SHA-256 HMAC digest and prefix for this header.
- The receiver must compare the provider value with its expected digest over the payload.
header: X-Hub-Signature-256
value format: sha256=<hex digest>
signed material: payload contents
secret: configured webhook secret
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The verifier follows GitHub’s documented header contract.
Why this result follows: Signature formats are provider-specific rather than universal.
8. Signed timestamp freshness
Problem: Check a fictional provider’s signed time window.
- The timestamp is four minutes old on the controlled clock.
- It is inside the fictional five-minute tolerance and is covered by the signature.
fictional signed timestamp: 12:00:00 UTC
verification clock: 12:04:00 UTC
allowed age: 5 minutes
signature covers timestamp and body
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The freshness check passes if the signature also verifies.
Why this result follows: Freshness requires a trusted timestamp and an explicit tolerance.
9. Expired signed timestamp
Problem: Reject an old fictional delivery.
- The delivery is six minutes old according to the controlled clock.
- That exceeds the fictional provider policy’s five-minute tolerance.
fictional signed timestamp: 12:00:00 UTC
verification clock: 12:06:00 UTC
allowed age: 5 minutes
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The freshness check rejects the old delivery.
Why this result follows: A valid signature can still be outside an allowed time window.
10. Unsigned timestamp
Problem: Avoid trusting a mutable freshness header.
- The signature covers the body but not the separate timestamp header.
- A modified timestamp could appear fresh without invalidating that body signature.
body signature: valid
timestamp header: not included in signed material
attacker can alter timestamp: yes
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The unsigned timestamp alone cannot establish freshness.
Why this result follows: Replay controls must authenticate the data on which they rely.
11. Duplicate within window
Problem: Deduplicate two verified copies of one event.
- Both requests pass the configured authenticity checks.
- The second uses the same stable event ID as an already accepted receipt.
event ID: evt-4
first verified delivery: receipt inserted, effect applied
second verified delivery: receipt already exists, no second effect
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The business effect occurs once in the fixture.
Why this result follows: A freshness window does not eliminate duplicate delivery.
12. Concurrent receipt race
Problem: Use a unique constraint for simultaneous duplicates.
- Both workers can observe an absent receipt before either insert commits.
- The database constraint arbitrates the competing event identity.
A: verified evt-5, receipt lookup absent
B: verified evt-5, receipt lookup absent
A and B: insert receipt
unique event constraint: one succeeds
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: Only one receipt association commits under the fixture constraint.
Why this result follows: A check-then-insert sequence alone cannot prevent the race.
13. Atomic receipt and intent
Problem: Persist verified acceptance with a processing job.
- The verified receipt and processing intent share a local transaction.
- A successful commit makes both available to a recovery worker.
with session.begin():
session.add(Receipt(provider="P", event_id="evt-6"))
session.add(Job(event_id="evt-6", status="pending"))
# successful commit -> both rows persist
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The receipt and pending job commit together.
Why this result follows: Atomic local persistence prevents an accepted receipt without its intended job.
14. Failure before commit
Problem: Avoid acknowledging a lost intent as durable.
- Verification succeeds but the database transaction fails.
- Rollback removes the pending receipt and job writes.
verify evt-7 -> valid
insert receipt and job -> database error
transaction -> rollback
response -> provider-compatible retryable error
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The endpoint does not claim durable acceptance in this fixture.
Why this result follows: Authenticity does not make failed persistence durable.
15. Lost acknowledgement
Problem: Handle a provider retry after receipt commit.
- The first request durably records acceptance before its response is lost.
- The verified retry finds the same receipt and avoids creating another job.
first evt-8: verified, receipt + job committed, response lost
retry evt-8: verified, receipt already exists
policy: acknowledge duplicate without second job
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: One receipt and one job remain in the fixture.
Why this result follows: Durable deduplication makes lost acknowledgements recoverable.
16. Conflicting event content
Problem: Handle a repeated ID with different signed bytes.
- The event identifier matches an existing receipt.
- The signed content hash differs, so silently treating it as the same event hides a conflict.
stored receipt: provider P, event evt-9, body hash A
new verified request: provider P, event evt-9, body hash B
policy: quarantine conflict
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The fixture quarantines the mismatch for review.
Why this result follows: A stable ID association needs a policy for conflicting content.
17. Scoped event identity
Problem: Keep provider accounts from colliding.
- The fictional provider guarantees uniqueness only within an account.
- Including account in the constraint distinguishes the two valid events.
unique receipt key: (provider, account, event_id)
account A sends evt-10
account B sends evt-10
provider contract: IDs unique per account
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The two accounts can each have their own evt-10 receipt.
Why this result follows: Deduplication scope must match the provider’s identity contract.
18. Worker retry after remote send
Problem: Handle a crash after an external effect.
- The worker cannot know from its missing mark whether the remote action occurred.
- The retry retains the stable key under the assumed provider guarantee.
worker sends operation key=evt-11 -> provider accepts
worker crashes before completion mark
retry uses key=evt-11; provider supports deduplication
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The fixture represents one logical remote effect.
Why this result follows: A local job record alone cannot undo or deduplicate a remote action.
19. Body size boundary
Problem: Reject an oversized delivery before unbounded work.
- The delivery exceeds the explicitly configured input budget.
- The server or application rejects it before accepting a receipt in this fixture.
configured maximum body: 1 MiB
request body: 2 MiB
policy: reject at enforced boundary
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: The oversized delivery is not processed.
Why this result follows: Signature verification still needs bounded input and capacity.
20. Safe webhook diagnostics
Problem: Record verification failure without copying secrets.
- The record retains a reviewed failure category and safe correlation ID.
- It omits the signature, secret, and raw payload.
incoming signature: synthetic-signature
body: protected synthetic payload
log: {"event":"webhook_signature_invalid","request_id":"req-12"}
Illustrative FastAPI or webhook trace; fictional protocol, synthetic secrets and isolated fixtures are assumed unless named.
Expected result: Operators can count the failure without exposing the protected values.
Why this result follows: Allowlisted diagnostics reduce accidental disclosure of webhook material.
Common errors and fixes
A valid event is applied twice
- Why it happens
- A correct signature was mistaken for replay protection.
- How to fix it
- Store and atomically enforce a stable event identifier.
- Prevent it next time
- Test concurrent and repeated deliveries.
A valid signature fails after JSON parsing
- Why it happens
- The checked bytes differ from the provider’s signed bytes.
- How to fix it
- Verify the documented raw representation before parsing.
- Prevent it next time
- Use provider test fixtures and a one-byte tampering case.
A committed event is lost after an early acknowledgement
- Why it happens
- The server acknowledged before work was durably recorded.
- How to fix it
- Persist the accepted intent before acknowledging according to the contract.
- Prevent it next time
- Simulate process failure and rehearse recovery.
20 practice exercises
1. The same correctly signed event arrives twice. What should the service check?
Show hint
Verify both requests and use a durable scoped event identity.
Show worked solution
Verify each request, then use a unique stable event ID to identify an already accepted event. Avoid repeating its business effect and return the provider-compatible response. Test concurrent duplicates as well as sequential retries.
Verify each delivery first, then use the provider’s stable event ID and an atomic uniqueness mechanism to identify the already accepted event. Return a provider-compatible response without repeating the business effect, and test concurrent as well as sequential duplicates.
Check your solution
- The second verified delivery does not create a second effect.
- Concurrent duplicates cannot both commit the same receipt.
2. Why is parsing and serializing JSON before signature verification risky?
Show hint
Compare the signed byte sequences rather than parsed JSON meaning.
Show worked solution
Whitespace, key ordering or encoding can change the bytes even when the data appears equivalent. Verify the exact bytes required by the provider’s specification, then parse and validate the event schema.
Parsing and reserializing can change whitespace, key order, or encoding even when the resulting object appears equivalent. Verify the exact bytes required by the provider’s specification before parsing and validating the event schema.
Check your solution
- The verifier receives the original signed bytes.
- A byte change fails the signature fixture.
3. A fictional provider signs UTF-8 raw bytes. The receiver normalizes Unicode text before checking the signature. Design a test using composed é and decomposed e plus U+0301.
Show hint
Canonical equivalence does not make the received byte sequences identical.
Show worked solution
Create two valid JSON bodies, one containing composed é and the other e followed by U+0301, encode each as UTF-8, and sign each exact byte sequence under the fictional contract. Assert each original body verifies with its own signature, while swapping signatures fails without a receipt. Verify before Unicode normalization or parsing changes the signed representation.
Check your solution
- Each original byte sequence verifies with its own signature.
- A swapped signature is rejected without creating a receipt.
4. A fictional provider signs timestamp + "." + raw body. A middleware parses and reserializes JSON before verification. Identify both signed-material risks and a test.
Show hint
The timestamp and body must be combined exactly as the provider specifies.
Show worked solution
Preserve the received timestamp representation and raw body bytes, then construct the signed material according to the fictional contract without JSON reserialization. Test the original signed request as a success control and a whitespace-altered body with the old signature as a rejection, with no receipt on failure.
Check your solution
- The exact timestamp and body combination verifies.
- Changing body whitespace with the old signature is rejected without a receipt.
5. A fictional HMAC header can be malformed, have a valid-format wrong digest, or match. Design a three-case verifier test.
Show hint
Validate the provider-defined format before constant-time digest comparison.
Show worked solution
Parse and validate the documented header format, calculate HMAC over its specified signed bytes, and compare compatible digest values with hmac.compare_digest. Assert malformed and wrong-digest inputs are rejected before receipt creation; the correctly formatted matching control is accepted once.
Check your solution
- Malformed and wrong digests create no receipt.
- A correctly formatted matching digest is accepted once.
6. An endpoint requires a signature header and limits bodies to 1 MiB. A request has no signature and a body within that limit. Design a test of the early rejection path.
Show hint
A missing required header can be rejected before expensive verification or durable work.
Show worked solution
Send a bounded synthetic body without the required header to an instrumented receiver. Assert the documented provider-compatible error, zero verifier calls, and no receipt or job. A separate properly signed request should reach verification; enforce the body limit independently of header presence.
Check your solution
- The missing-header request does not invoke the verifier or create durable work.
- A properly signed control reaches verification.
7. Two provider accounts use different synthetic signing keys. A request for account A is signed with B’s key. Design a cross-account verification test.
Show hint
Key selection must follow trusted account configuration, not an unverified payload claim.
Show worked solution
Under the fictional account-routing contract, select A’s configured key using a trusted endpoint or other verified context. Assert a request presented on A’s route with B’s signature is rejected without a receipt, then assert the same body signed with A’s key is accepted. Do not log either key.
Check your solution
- B’s signature is rejected on the trusted A route without a receipt.
- A correctly signed control is accepted on A’s route.
8. A signed delivery arrives twice within its allowed timestamp window. Does freshness prevent duplication?
Show hint
Freshness and unique event acceptance address different problems.
Show worked solution
No. Verify each request and use a durable unique event identity to recognize the already accepted delivery. Return the provider-compatible duplicate response without repeating the protected effect.
Check your solution
- Both deliveries are verified.
- The same event causes one logical effect.
9. A fictional provider signs a timestamp and permits age up to five minutes inclusive, with no future timestamps allowed. Evaluate deliveries at 12:05:00 and 12:05:01 for a 12:00:00 signature.
Show hint
Use the stated inclusive boundary and fixed verification times.
Show worked solution
Assuming signature verification succeeds, the first delivery is exactly five minutes old and passes this fixture’s freshness rule; the second is five minutes and one second old and fails. Test with a fixed clock and keep the provider’s real timestamp format separate.
Check your solution
- At 12:05:00 the signed timestamp passes the inclusive limit.
- At 12:05:01 it fails the limit.
10. A fictional provider signs body and timestamp together. An attacker changes only the timestamp to make an old delivery appear fresh. What should verification and receipt tests show?
Show hint
Changing signed material must invalidate the original signature.
Show worked solution
Recompute the expected signature using the received timestamp and exact raw body under the stated contract. Assert the altered timestamp with the old signature is rejected before receipt creation; a correctly signed fresh control can be accepted, subject to the event’s durable deduplication policy.
Check your solution
- The altered signed timestamp invalidates the old signature and creates no receipt.
- A correctly signed fresh control passes signature and freshness checks.
11. Two verified deliveries of the same scoped event race. One inserts a receipt but its job insert fails and that transaction rolls back. Explain both possible competitor outcomes and the later retry.
Show hint
A rollback does not determine whether the other transaction subsequently commits.
Show worked solution
Store receipt and job atomically with a scoped unique constraint. If the competitor commits the pair, the later verified retry detects the existing receipt and follows the duplicate acknowledgment policy without another job. If neither initial transaction commits, the later retry can commit one pair. Coordinate and test each outcome on the selected database; in both, exactly one receipt and one job remain after successful recovery.
Check your solution
- A committed competitor makes the later retry deduplicate.
- If neither initial attempt commits, the retry can commit one receipt and one job.
12. A provider sends a verified event, but the database transaction that stores its receipt and job fails. What acknowledgement and retry behavior should the receiver use?
Show hint
A failed commit cannot establish durable acceptance.
Show worked solution
Roll back both writes and return the documented failure response so the provider can retry under its contract. On a later verified retry, attempt the atomic receipt and job transaction again; do not claim the event is durably accepted before commit.
Check your solution
- Neither receipt nor job remains committed after rollback.
- A retry can be processed and acceptance follows a successful commit.
13. The receipt and job commit, but the success acknowledgment is lost. The provider retries twice with the same verified bytes. Design an acceptance and effect-count test.
Show hint
Acknowledgment delivery is distinct from durable local acceptance.
Show worked solution
After the first commit simulate lost response, then send two verified retries of the same scoped event and body. Assert each receives the provider-compatible duplicate acknowledgment under the chosen policy, while only one receipt and one job exist and the protected effect is not repeated.
Check your solution
- The two retries receive the documented duplicate acknowledgment.
- One receipt and one job remain without a repeated effect.
14. An attacker submits an invalidly signed request claiming event ID evt-9 before the genuine delivery arrives. Explain why the receiver must not reserve that ID and design a regression test.
Show hint
Establish authenticity before trusting an event identifier for deduplication.
Show worked solution
Reject the invalid signature without inserting a receipt or job for evt-9. Then submit a correctly signed genuine delivery with that ID and assert it is accepted once and creates its receipt and job. This prevents an unauthenticated request from poisoning the deduplication record.
Check your solution
- The invalid delivery creates neither receipt nor job.
- The later genuine delivery is accepted and persisted once.
15. Provider P guarantees event IDs only per account. Accounts A and B both send evt-10, then A retries its event. Derive the receipt and job counts.
Show hint
Use the verified provider, account, and event ID as the stated scope.
Show worked solution
Assuming both accounts and signatures are verified, commit separate scoped receipts and jobs for A/evt-10 and B/evt-10. Treat A’s matching retry as a duplicate. The final state is two receipts and two jobs, with no third job from the retry.
Check your solution
- The two accounts each have one receipt and one job.
- A’s retry creates no third receipt or job.
16. A worker’s external action succeeds, but it crashes before marking the job complete; the provider’s idempotency retention has expired at restart. Define recovery.
Show hint
A stable key cannot be assumed effective beyond the provider’s guarantee.
Show worked solution
Do not blindly resend the action after the documented key window. Use the provider’s supported operation lookup or a manual reconciliation path to establish the outcome; only retry if its protocol makes that safe. Test the expired-key case with a synthetic provider and assert no unprotected duplicate effect.
Check your solution
- The expired key is not assumed to deduplicate a new action.
- Recovery reconciles before any potentially duplicating retry.
17. A delivery has no trustworthy Content-Length and arrives in chunks. The policy allows at most 1 MiB. How should an enforced boundary handle it?
Show hint
A declared size alone cannot bound a streamed body.
Show worked solution
Count received bytes at the configured transport or application boundary and stop accepting the body when the limit is exceeded, according to the server’s supported behavior. Assert a 1 MiB synthetic body follows the ordinary verification path, while a larger chunked body is rejected with no receipt or job.
Check your solution
- A body at the limit reaches normal verification.
- A body exceeding the limit is rejected without receipt or job.
18. A webhook secret rotates from key A to key B. What should the receiver test?
Show hint
Use only the provider-supported rotation protocol.
Show worked solution
Test the documented overlap or key-selection procedure with synthetic old and new keys, then verify that retired keys are no longer accepted after the transition. Never log the secrets.
Check your solution
- Both permitted transition cases are tested.
- The retired key is rejected after retirement.
19. A signature exception message embeds a synthetic signature and payload marker. Design a test of the full diagnostic output.
Show hint
Check formatted exception text as well as structured fields.
Show worked solution
Trigger the failure using unique synthetic markers and capture the rendered log including any exception text. Assert the approved failure category and safe request ID are present while neither signature nor payload marker appears. Keep any public error response equally free of those values.
Check your solution
- The log retains the approved category and safe request ID.
- Neither marker appears in the full log or public error.
20. A TestClient test verifies a synthetic HMAC using a fake store. What production claims remain unproven?
Show hint
The fixture does not exercise every external boundary.
Show worked solution
It verifies local routing and controlled signature decisions, but not production proxy byte preservation, real database races, provider connectivity, or external delivery. Test each separately in an authorized isolated environment.
Check your solution
- The local verification behavior is observed.
- Unexercised transport and storage guarantees are not claimed.
Key takeaways
- Signature validation and replay prevention are distinct controls.
- Durable acceptance and idempotent effects require explicit transaction boundaries.
- Verify the exact signed bytes before parsing and applying effects.
- A valid signature does not prevent duplicate or replayed deliveries.
- Durable unique receipts and retry-safe effects require explicit transactional boundaries.