Retry Logic
Retry logic is the disciplined re-attempting of failed requests using exponential backoff with jitter and a retry cap, combined with idempotency keys so that retrying an order can never place a duplicate.
Quick answer: Retry logic is the disciplined re-attempting of failed requests using exponential backoff with jitter and a retry cap, combined with idempotency keys so that retrying an order can never place a duplicate.
In simple words
Retry logic is how your code recovers from temporary failures without making things worse. Instead of instantly re-sending a failed request, it waits a little, then a bit longer, adding randomness so many clients do not retry in sync. And for orders it uses a safeguard — an idempotency key — so that even if it retries, the broker will not create a second order.
Purpose
Retry logic exists because transient failures are inevitable, but naive retrying causes two disasters — synchronised retry storms that worsen an outage, and duplicate orders — so it must be engineered, not improvised.
Professional explanation
Why fixed-interval retries fail
The simplest retry — wait one second, try again, repeat — is also the most dangerous at scale. If a broker has a brief outage, every client using fixed intervals retries at the same moments, producing a synchronised thundering herd that prolongs the outage exactly when the server is trying to recover. Fixed short intervals also give up too fast on longer problems or hammer too hard on shorter ones. Effective retry logic instead spreads attempts out over increasing intervals and desynchronises clients from each other. The goal is to give a struggling dependency room to recover while still recovering your own request promptly.
Exponential backoff
Exponential backoff increases the wait between attempts geometrically: for example roughly 1 second, then 2, then 4, then 8, typically as base times a growth factor raised to the attempt number. This means the first retry is quick (handling a momentary blip) while later retries space out (handling a longer outage without pounding the server). The parameters — base delay and multiplier — are tuned to the failure profile. Backoff alone, however, is not enough, because if all clients start their backoff at the same instant they remain synchronised at every doubling; that is what jitter fixes.
Jitter: breaking synchronisation
Jitter adds randomness to each backoff delay so that clients spread their retries across time rather than firing together. A common scheme is full jitter — instead of waiting exactly the computed delay, wait a random amount between zero and that delay — which turns a synchronised herd into a smooth, uniform load on the recovering server. Without jitter, exponential backoff still leaves clients aligned at 1s, 2s, 4s and so on; with jitter, their attempts scatter. For any system where many instances or many symbols retry against the same broker, jitter is not optional polish but the mechanism that prevents self-inflicted retry storms.
Caps: giving up safely
Retries must be bounded on two axes: a maximum number of attempts and a maximum total elapsed time, plus a ceiling on the individual backoff delay so it does not grow to minutes. Unbounded retries are dangerous in trading: a retry that finally succeeds ten minutes later may place an order into a completely different market, which is worse than not placing it. When the cap is reached, the request is declared failed and escalated — logged, alerted, and on critical paths handed to the kill switch or a human. The cap encodes a judgement that beyond a certain point, acting late is worse than not acting, which is especially true for time-sensitive order flow.
Idempotency keys: the safeguard for orders
The special hazard of retrying is duplication: retry a create-order request whose response was merely lost, and you place the order twice. An idempotency key solves this. The client generates a unique key per logical order and sends it with the request; the broker records that key and, if it sees the same key again, returns the original result instead of creating a new order. Where a broker supports a client-order-id or tag, that becomes your idempotency key; where it does not, you emulate the guarantee by querying the order book for your reference before retrying. The rule is absolute: never retry an order-creating request without an idempotency mechanism, because the network can always fail after the order was accepted but before you learned of it.
What to retry — and what never to
Retry logic applies only to transient, retry-safe failures: timeouts, 429s (respecting Retry-After), 5xx, and connection blips. Permanent errors — 400, invalid instrument, insufficient funds — must not be retried, since they will fail identically and, for rate limits, harmfully. Read operations (GET positions, GET quotes) are naturally idempotent and safe to retry freely. State-changing operations need care: cancels are usually idempotent and retry-safe, but creates are not and require the idempotency key. Encoding which operations and which error codes are retryable, rather than blindly retrying everything, is what separates safe retry logic from a duplicate-order generator.
Formula
delay = min(cap, base × factor^attempt) × random(0, 1)
Exponential backoff with full jitter. base = initial delay (e.g. 1s), factor = growth (e.g. 2), attempt = retry number, cap = maximum delay ceiling. The random(0,1) multiplier is the jitter that desynchronises clients. Bound total attempts and total elapsed time separately.
Naive retry vs engineered retry
| Aspect | Naive (fixed interval) | Engineered (backoff + jitter + idempotency) |
|---|---|---|
| Timing | Same interval every time | Growing, randomised delays |
| Effect on outage | Thundering herd | Smooth, recoverable load |
| Order safety | Can double-send | Idempotency key prevents duplicates |
| Termination | Often unbounded | Capped attempts and elapsed time |
| Applies to | Everything blindly | Only retry-safe errors |
Practical example
Illustrative example (Indian market)
Your system sends a cancel request that times out. Retry logic waits a jittered delay — a random value up to about 1 second — then retries; still failing, it waits up to about 2 seconds, then up to 4, capping at, say, 5 attempts within 15 seconds. Cancel is idempotent, so repeats are safe. Separately, a place-order request times out. Because create is not idempotent, the client does not simply retry: it attached a unique client order id, so it first queries the order book for that id. Finding no such order, it safely retries once with the same id; had the order existed, it would have adopted it instead of duplicating. All figures are illustrative.
With Indian broker APIs that expose a tag or client-order-id field on order placement, that field is your idempotency key: set it to a unique value per intended order, and after any timeout query orders by that tag before retrying. Where an API offers no such field, emulate idempotency by listing recent orders and matching on symbol, side, quantity and timestamp before deciding to re-send.
Advantages
- Recovers automatically from the transient failures that dominate real-world API use
- Exponential backoff with jitter prevents self-inflicted retry storms during outages
- Idempotency keys make order retries safe, eliminating duplicate-order risk
- Caps ensure the system fails fast and escalates rather than acting dangerously late
Limitations
- Adds real complexity — backoff, jitter, caps and idempotency must all be correct
- A late successful retry can act into a changed market, so time caps are essential
- Idempotency depends on broker support or careful emulation via state queries
- Retrying the wrong error class (permanent, rate-limited without backoff) causes harm
- Retries can mask a persistent underlying problem if breaches are not also monitored
Common mistakes
- Retrying create-order requests without any idempotency key, causing duplicate orders
- Using fixed intervals with no jitter, producing synchronised retry storms
- Leaving retries unbounded, so an order can be placed minutes late into a different market
- Retrying permanent errors (400, insufficient funds) that will only fail again
- Ignoring Retry-After on a 429 and retrying too aggressively into a ban
- Not escalating when the retry cap is reached, silently dropping a critical action
Professional usage
Professional clients implement retry as a reusable policy layered into the transport: a decorator or middleware that knows which status codes and operations are retry-safe, applies exponential backoff with full jitter, honours Retry-After, and enforces attempt and time caps. Order-creating calls always carry a client-generated idempotency key, and on any ambiguous outcome the client reconciles against the order book rather than blindly re-sending. Retry counts and cap breaches are emitted as metrics so a rising retry rate flags a degrading dependency before it becomes an outage.
Key takeaways
- Retry only transient, retry-safe failures — never permanent errors, and respect Retry-After
- Use exponential backoff with jitter to recover promptly without causing a thundering herd
- Cap attempts, total time and individual delay, then escalate — acting very late can be worse than not acting
- Never retry an order-create without an idempotency key or a state query, or you risk duplicate orders
Frequently asked questions
What is retry logic?
What is exponential backoff?
Why add jitter to retries?
What is an idempotency key?
Why is retrying an order dangerous without idempotency?
Should I retry every failed request?
Why cap the number of retries?
What is a thundering herd?
Is a cancel safe to retry?
What is full jitter?
How do I emulate idempotency if the broker has no key field?
What should happen when retries are exhausted?
Does retry logic replace error classification?
Voice search & related questions
Natural-language questions people ask about Retry Logic.
What is retry logic in simple words?
What is exponential backoff?
Why add randomness to retries?
How do I stop retries from double-placing an order?
Should I keep retrying forever?
Which errors should I retry?
Sources & references
Last reviewed 11 July 2026. Educational content only — not investment advice. Markets and rules change; verify current conventions with SEBI, NSE/BSE and your broker.