Tech challenge · Python

Retries create duplicate records

HardPython

An ingestion job calls a partner API and writes each response to your warehouse. To survive timeouts you wrapped the call in a retry loop. Now the warehouse has duplicate orders on busy days. Explain why, and design a retry that is safe.

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

A timeout does not tell you whether the other side did the work. Make repeating an operation harmless.

Show the solution

A timeout can happen after the write succeeded, so the retry writes again. Retries are only safe when the operation is idempotent. Write with a natural key (the order id) using an upsert or MERGE so repeats overwrite instead of inserting, or pass an idempotency key if the API supports one. Retry only transient errors, with exponential backoff and jitter so many workers do not retry in lockstep, and cap the attempts.

Example (Python)

import random, time

class Transient(Exception):
    pass

def with_retries(fn, attempts=5, base=0.5, cap=30):
    for n in range(attempts):
        try:
            return fn()
        except Transient:
            if n == attempts - 1:
                raise
            time.sleep(min(cap, base * 2 ** n) * random.uniform(0.5, 1.5))

# the write must be idempotent, e.g. MERGE INTO orders USING batch ON order_id ...

Common mistakes

  • Retrying every exception, including 4xx validation errors that will never succeed.
  • Retrying instantly in a tight loop, which turns a short outage at the partner into a self-inflicted overload.
  • Deduplicating later in reporting instead of making the write idempotent.

Learn more

More Python challenges

Today's challenge and the full archive