📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A partner's integration starts retrying aggressively against your payments API: some customers are charged twice and the API slows down for every other partner. Walk me through how you would handle the incident, fix it with idempotency keys and rate limits, and work with the partner so it doesn't happen again.

Handling a partner retry storm on a payments API: incident triage, refunds, rate limits per partner, idempotency keys, Retry-After and error contracts, partner communication and long-term API governance.

Senior RealWorldScenario Advanced idempotency-keys incident-response partner-apis payments rate-limiting web-api

🎯 Key points

  • Stabilise first: throttle or suspend the partner's subscription at the gateway, protect other partners
  • Quantify impact: find duplicate payments, refund and notify, check obligations (scheme rules, Privacy Act if data exposed)
  • Root cause on both sides: partner retries without backoff; API had no idempotency and no per-partner limits
  • Idempotency-Key: atomic claim, stored response replayed on retry, 409 for an in-progress twin, 422 for a different body, same transaction as the payment, forwarded to the provider
  • Per-partner token bucket (ASP.NET Core rate limiter, API unchanged since .NET 7) and APIM quotas, with 429 + Retry-After
  • Retry contract: retryable statuses, exponential backoff with jitter, honour Retry-After; in docs and SDKs
  • Communicate: incident channel with the partner, timeline, written blameless post-incident review
  • Prevent: alerts on per-partner traffic spikes and duplicate candidates, usage baselines, sandbox certification

⏱ 30-second answer

First stabilise: rate limit or temporarily suspend the partner's subscription at the gateway so other partners recover, and stop the bleeding on duplicates. Then quantify and repair: find duplicate charges by account, amount and time, refund them and tell affected customers through the partner. The root cause usually sits on both sides: the partner retried on timeouts with no backoff, and our API had no idempotency and no per-partner limits. The fix is to require an Idempotency-Key on payment POSTs: claim it atomically, store the response in the same transaction as the payment and replay it on retries, return 409 while a twin is in progress and 422 for a reused key with a different body, and forward the key to the provider. Add per-partner token buckets with 429 + Retry-After, and publish a retry contract (backoff with jitter). Finish with a blameless review and certification tests.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd handle it in three stages: stabilise, repair, prevent. Stabilising means protecting money and other partners. At API Management I'd drop that partner's subscription to a low rate limit, or suspend it if duplicates are still happening, and call their on-call contact so they know why. The other partners should recover within minutes, and duplicate charges stop growing.

For example, at [company] we [had a partner whose batch job retried every failed payment immediately after a database slowdown]. I [pulled duplicates from SQL by matching account, amount and a short time window, about [N] customers], we refunded them the same day, and the partner notified their customers. The root cause was on both sides. Their client retried on timeouts with no backoff and generated a new request each time. We had no idempotency, so a request that succeeded after their timeout was charged again on retry, and we had a single shared limit, so one partner could exhaust capacity for all [N] partners. The fix was an Idempotency-Key header required on every payment POST, recorded in the same transaction as the payment and forwarded to our payment provider; per-partner token buckets returning 429 with Retry-After; and a written retry contract. Duplicates went to [zero] and the next retry storm only affected that partner's own traffic.

The mistake I see is treating it as only the partner's bug. They should fix their backoff, but our API made duplicates possible. A senior answer owns both halves: make the API safe against misbehaving clients, and make it easy for clients to behave."


Stage by stage

Stage Actions Tools
Detect Alerts: per-partner request rate, payment duplicates, latency Application Insights, APIM analytics
Stabilise Throttle or suspend the subscription; shed load with 503 + Retry-After APIM policies, feature flags
Repair Find duplicates, refund, notify through the partner SQL queries, provider dashboard
Root cause Trace requests; review partner client behaviour End-to-end transactions, partner logs
Fix Idempotency keys, per-partner limits, retry contract ASP.NET Core rate limiter, SQL unique index
Prevent Certification tests, alerts, docs, SDK Sandbox environment, developer portal

Communication

Audience Message
Partner Immediate call, what we did to their traffic and why, joint timeline
Internal Incident channel, status updates every 30 minutes, finance for refunds
Customers Through the partner, with refunds confirmed
Leadership Impact (customers, dollars), cause, fixes and dates

Production example

In a [payments platform] serving [25] partners, one partner's retry loop created [180] duplicate payments in [40 minutes] and pushed everyone's p95 from 300 ms to 4 s. After idempotency keys, per-partner limits and a retry contract, a similar partner bug [six months later] produced zero duplicates and other partners' p95 didn't move.

🔍 What the interviewer is checking

Checks incident leadership, technical judgement on idempotency and rate limiting, and the ability to manage an external partner.

Green flags

  • Stabilises before investigating and protects other partners
  • Quantifies impact and handles refunds carefully
  • Fixes the API side (idempotency, per-partner limits, retry contract), not just the partner
  • Plans a phased rollout and communicates clearly
  • Runs a blameless review with prevention items

Red flags

  • "Tell the partner to fix their code" and nothing else
  • Jumps to code changes during the incident
  • No mention of refunds or customer impact

📚 Learn in depth

1. Why retries cause duplicates

partner --POST /payments--> API --> provider: charge OK, DB commit OK
partner   (times out at 5 s; response arrives at 6 s)
partner --POST /payments--> API --> provider: charge again

Any non-idempotent write behind a client timeout can be duplicated. Only a client-supplied operation identity (an idempotency key) or a natural business key (the partner's own payment reference with a unique constraint) lets the server recognise the retry.

2. Why one partner slowed everyone

Without partitioned limits, every partner shares the same capacity: thread pool, connection pool (100 by default), provider quota. A retry storm from one client consumes it all. Per-partner token buckets give each partner a fair share; a concurrency limiter in front of the provider stops slow calls piling up.

3. Triage queries

-- Candidate duplicates: same partner, account and amount within 2 minutes
SELECT p1.Id, p2.Id AS DuplicateId, p1.PartnerId, p1.AccountId, p1.Amount, p1.CreatedAt, p2.CreatedAt
FROM dbo.Payments p1
JOIN dbo.Payments p2
  ON p2.PartnerId = p1.PartnerId AND p2.AccountId = p1.AccountId AND p2.Amount = p1.Amount
 AND p2.CreatedAt > p1.CreatedAt AND p2.CreatedAt <= DATEADD(MINUTE, 2, p1.CreatedAt)
WHERE p1.CreatedAt >= @IncidentStart;

Review candidates manually or with the partner: some may be real repeat payments.

4. Designing the fix

  • Idempotency key: required header, scoped per partner, request fingerprint, stored response, same transaction as the payment, 24-hour retention, forwarded to the provider.
  • Natural key: if partners send their own payment reference, a unique index on (PartnerId, PartnerReference) is a strong second line.
  • Limits: per-partner token bucket in the app for instance protection; contractual quotas in API Management.
  • Error contract: 429 + Retry-After for limits, 503 + Retry-After for shedding, 409 for an idempotency key in progress, 422 for a reused key with a different body. ProblemDetails everywhere.
  • Rollout: make the key optional and log its absence, give partners a deadline, then require it (400 without it).

5. Partner management

Partners are customers. A good API team publishes retry guidance, ships SDKs that implement it, offers a sandbox with fault injection ("return 503 for 10% of calls") and certifies new integrations against it.

6. Obligations

Duplicate charges are a financial incident: refunds, card scheme rules, possibly ASIC or AUSTRAC reporting depending on the business. If personal data was exposed, assess under the Notifiable Data Breaches scheme. Know who decides these before an incident.

Try it yourself

  1. Simulate a partner client with a 2 s timeout and immediate retries against an endpoint that takes 3 s; count duplicates.
  2. Add Idempotency-Key handling and repeat.
  3. Add a per-partner token bucket and a second well-behaved client; compare its latency before and after.
  4. Write the duplicate-detection query and run it against your test data.
  5. Draft a one-page retry contract for partners.

💻 Code

The two server-side controls side by side: a per-partner limit and a required idempotency key, with clear error contracts.

using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.AddPolicy("per-partner", ctx => RateLimitPartition.GetTokenBucketLimiter(
        ctx.User.FindFirst("partner_id")?.Value ?? "unknown",
        _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 50, TokensPerPeriod = 10,
            ReplenishmentPeriod = TimeSpan.FromSeconds(1), QueueLimit = 0
        }));
    o.OnRejected = (ctx, _) =>
    {
        if (ctx.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan wait))
            ctx.HttpContext.Response.Headers.RetryAfter = ((int)Math.Ceiling(wait.TotalSeconds)).ToString();
        return ValueTask.CompletedTask;
    };
});

builder.Services.AddAuthentication(/* partner client credentials via Entra ID */);
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();

app.MapPost("/payments", (HttpContext http, CreatePayment body) =>
    {
        // Rollout phase 2: the key is required. Phase 1 only logged its absence.
        if (!http.Request.Headers.ContainsKey("Idempotency-Key"))
            return Results.Problem(
                title: "Idempotency-Key required",
                detail: "Send a unique Idempotency-Key per payment and reuse it on retries. See /docs/retries.",
                statusCode: 400);

        // Claim the key, create the payment and store the response in one transaction
        // (see the idempotency key implementation), forwarding the key to the provider.
        return Results.Created($"/payments/{Guid.CreateVersion7()}", body);
    })
    .RequireAuthorization()
    .RequireRateLimiting("per-partner");

app.Run();

public sealed record CreatePayment(string PartnerReference, string AccountId, decimal Amount, string Currency);

⚠ Common mistakes

  • Mistake: Debugging before stabilising. Why it is wrong: duplicates and the outage keep growing while you investigate. Instead: throttle or suspend the offending traffic first, then investigate.
  • Mistake: Blaming the partner and stopping there. Why it is wrong: the next partner with the same bug causes the same incident. Instead: make the API safe against misbehaving clients with idempotency and per-partner limits.
  • Mistake: Silently blocking the partner. Why it is wrong: they see failures with no explanation and may retry harder or escalate commercially. Instead: call them, explain what you did and agree next steps.
  • Mistake: Refunding by guesswork. Why it is wrong: some "duplicates" are legitimate repeat payments. Instead: identify candidates with a query, confirm with the partner and refund confirmed duplicates.
  • Mistake: Requiring idempotency keys overnight. Why it is wrong: every partner without the header breaks. Instead: phase it in: log, warn, then require by an agreed date.
  • Mistake: Rate limiting with a single global limiter. Why it is wrong: the noisy partner still consumes everyone's capacity. Instead: partition limits per partner.
  • Mistake: No written review. Why it is wrong: lessons stay in a few heads. Instead: a blameless post-incident review with owners and dates.

🏛 Senior insight: trade-offs

What makes this senior is owning both sides. A partner's bug triggered the incident, but our API design (no idempotency, shared capacity, vague retry guidance) turned a client bug into customer harm. I fix our side so that the next misbehaving client can only hurt itself, and I make good behaviour easy with SDKs, docs and a sandbox that injects failures.

The other senior skill is communication under pressure: the partner is a customer, finance needs numbers, leadership needs a clear story. I'd keep a timeline from the first alert, because the post-incident review and any regulatory questions depend on it.

Option When it fits Cost When not to
Suspend the partner's subscription Duplicates still happening, money at risk Partner outage, commercial friction When a rate limit alone stops the harm
Tight per-partner rate limit Overload without duplicates Partner sees 429s When each request may duplicate money
Idempotency key (required) Any money-moving endpoint Partner integration changes Naturally idempotent endpoints
Natural key unique constraint Partners send a stable reference Schema change Operations that may legitimately repeat

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes idempotency keys Why: Checks the implementation details: atomic claim, fingerprint, same transaction
    How to answer

    The client sends a unique Idempotency-Key (usually a UUID) with a non-idempotent request and reuses it on every retry. The server atomically claims the key with a unique constraint on (client, key), stores a fingerprint of the request, executes the operation and saves the response. A retry with the same key and body gets the stored response replayed; a request still in progress gets 409 Conflict; the same key with a different body gets 422. Ideally the business write and the idempotency record commit in one transaction, so a crash can't leave a charge without a record. Keys expire after a published window, often 24 hours. The trade-off is an extra write per request and storage, in exchange for making POST safe to retry.

  2. When: Candidate proposes per-partner rate limits Why: Checks configuration of partitioned limits in ASP.NET Core
    How to answer

    Register limiters with builder.Services.AddRateLimiter, add app.UseRateLimiter() after routing and authentication, then attach named policies to endpoints with RequireRateLimiting("name") or [EnableRateLimiting]. For fairness use RateLimitPartition.GetTokenBucketLimiter (or fixed/sliding window) keyed by the API key, user id or tenant so one client can't exhaust another's quota. Set RejectionStatusCode = 429 (the default is 503) and use OnRejected to copy the lease's RetryAfter metadata into the Retry-After header with a ProblemDetails body. The catch: the middleware keeps state in memory per process, so with several instances the effective limit multiplies; contractual limits belong in a shared store or the gateway.

  3. When: Candidate mentions publishing retry guidance Why: Checks the retry contract: retryable statuses, Retry-After, jitter
    How to answer

    A retry is only safe if the request is idempotent and the failure is transient. As the API owner I make both explicit: GET, PUT and DELETE are idempotent by design, POST takes an Idempotency-Key, and I document which statuses are retryable: network failures, 408, 429, 502, 503, 504, never 4xx validation or auth errors. When I shed load I return 429 or 503 with Retry-After, and clients should honour it. Clients must use exponential backoff with jitter so thousands of them don't retry in lockstep. The big risk is retry amplification: if three layers each try four times, one user click becomes 64 calls to the struggling service. Retry at one layer, cap it with a budget, and let a circuit breaker stop it.

🛠 Real-world problems: how you handle them

Partner retry loop double-charges customers and slows every partner
Situation
A [payments API] behind Azure API Management in Australia East serving [25] partners, about [60,000] payments a day. After a [database failover] slowed responses, one partner's batch job retried every timed-out payment immediately with a new request.
Signals
Requests from one partner jumping from [5] to [200] per second, p95 for all partners from [300 ms] to [4 s], provider reporting a spike in charges, finance and customer complaints about duplicate charges.
Investigation
APIM analytics by subscription showed one partner dominating traffic; Application Insights end-to-end transactions showed successful payments followed seconds later by identical requests; a SQL query matched duplicates by partner, account, amount and time window; the partner's logs confirmed 5 s timeouts and immediate retries.
Resolution
Suspended the partner's subscription for [20 minutes] after calling them, then restored it with a low rate limit. Refunded [180] confirmed duplicates the same day. Shipped required Idempotency-Key on payments (phased over [4 weeks]), per-partner token buckets with 429 + Retry-After, and a unique index on (PartnerId, PartnerReference).
Prevention
Alerts on per-partner traffic spikes and on duplicate candidates, a sandbox with fault injection that new partners must pass, retry guidance and SDK updates in the developer portal, and a blameless review shared with the partner.

How to tell it (STAR)

**S:** At [company], after a [database failover] one partner's batch job started retrying every slow payment immediately, double-charging [about 180] customers and slowing the API for all [25] partners. **T:** As [the on-call lead / tech lead] I had to stop the harm, fix the damage and make sure one partner's bug couldn't do this again. **A:** I called the partner and suspended their subscription for [20 minutes], which brought everyone else's p95 back down, then restored them behind a tight limit. I found duplicates with a SQL query, confirmed them with the partner and we refunded the same day. Then I led the fix on our side: required idempotency keys stored with the payment, per-partner token buckets returning 429 with Retry-After, and a published retry contract. **R:** When another partner had a similar bug [six months] later, there were [zero] duplicates and other partners' latency didn't move.

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me