A sync job that runs too fast can get your API key locked in week one
FDEs sit on both sides of a rate limit, and a few dozen lines of Python can back off on a 429 and cap your own API.
In brief
- When calling a client's API, throttle yourself first so you never hit the ceiling. If you still get a 429, follow Retry-After.
- Retrying without jitter performed worst in AWS's simulation, so always add a random interval.
- When you own the API, set rate limits at the gateway per API key and return 429 with headers that tell the client what to do.
The sync job ran 3,000 records, and it ran fast. That speed is why the client’s ERP system threw errors all night, and why, the next morning, the client’s IT team emailed to say they had suspended the API key until the job was fixed. Take this as a hypothetical first week on a client site; for an FDE it is an easy one to live through for real.
FDEs usually sit between two systems: they call APIs the client owns, and they expose their own APIs for the client’s systems to call. In the first direction, you have to be a well-behaved client. In the second, you have to set your own limits so that one faulty client cannot take the service down.
This guide covers both directions. You will write a client that reads the 429 signal and slows itself down, then a simple limiter that sits in front of your own API. The code is sketch-level Python, trimmed for readability, using only the standard library. You need Python 3, a terminal and a real or mock API to test against.
What does a rate limit actually protect?
MDN defines rate limiting as controlling the number of operations performed within a period of time, mainly so a system is not overloaded and slowed down. A server can limit the number of requests it accepts from a client in a given period, both to preserve performance and to mitigate attacks such as DoS.
Limits are often counted per client IP. If requests are authenticated or carry cookies, the limit may be counted per user or per application. On a client site, that means every job sharing one API key also shares one quota, and your sync job may be eating into the allowance of another internal application.
Start with simple arithmetic. Say the client’s API allows 10 requests per second and you need to sync 3,000 records, one request per record. The minimum time is 300 seconds, or 5 minutes. Any attempt to finish faster than 5 minutes only buys you errors.
Step 1: read the 429 and Retry-After signals correctly
HTTP 429 Too Many Requests means the client has sent too many requests in a given period. The limit may apply to the whole server or to individual resources. The server may include a Retry-After header saying how long the client should wait before trying again.
The trap is that Retry-After can take one of two forms. The first is an HTTP date; the second is a non-negative integer giving the number of seconds to wait. Code that handles only one form breaks the moment it meets a server using the other.
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone
def retry_after_seconds(value):
if value is None:
return None
value = value.strip()
if value.isdigit(): # seconds form
return int(value)
try: # HTTP date form
when = parsedate_to_datetime(value)
delta = (when - datetime.now(timezone.utc)).total_seconds()
return max(0, delta)
except (TypeError, ValueError):
return None
Check: retry_after_seconds("120") must return 120. For an HTTP date a few minutes from now, the result must be a positive number of seconds. For a garbage string, the function must return None rather than raise.
Step 2: retry with jitter when the server does not say how long to wait
Not every server sends Retry-After. Without it, the usual approach is exponential backoff: each retry waits twice as long as the one before. A post on the AWS Architecture Blog showed that plain backoff without jitter produced the worst results in their simulation, because many clients that fail at the same moment also retry at the same moment.
import random, time
def backoff_delay(attempt, base=1, cap=60):
return random.uniform(0, min(cap, base * 2 ** attempt))
def call_with_retry(send, max_attempts=5):
for attempt in range(max_attempts):
status, headers = send() # send() is your own placeholder function
if status != 429:
return status
wait = retry_after_seconds(headers.get("Retry-After"))
time.sleep(wait if wait is not None else backoff_delay(attempt))
raise RuntimeError("Out of retries")
Check: have a fake send() return 429 three times and then 200, and print the waits. They should be random and tend to grow, not an identical 1, 2, 4 on every run.
Step 3: do not wait for a 429 before slowing down
Retries are a safety net, not a strategy. A good client throttles itself from the start. MDN distinguishes two ideas: throttling still lets an operation run, but only at a fixed maximum rate, while debouncing collapses several closely spaced calls into one and waits until the calls stop altogether.
A sync job needs throttling. Debouncing suits things like a client-side search box.
Tyk compares several familiar algorithms. Fixed window is simple but vulnerable to bursts, sliding log is accurate but memory-hungry, and token bucket handles bursts flexibly. A token bucket works like a bucket: tokens are added at a fixed rate, each request takes one, and when the bucket is full new tokens are discarded.
class TokenBucket:
def __init__(self, rate, capacity):
self.rate, self.capacity = rate, capacity
self.tokens = capacity
self.last = time.monotonic()
def take(self):
now = time.monotonic()
self.tokens = min(self.capacity,
self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(rate=8, capacity=8) # 20% headroom below the 10/second ceiling
def throttled_send(send):
while not bucket.take():
time.sleep(0.05)
return call_with_retry(send)
Setting 8 instead of 10 leaves room for other applications sharing the key. It is a cautious choice, not a standard figure. Check: sending 80 requests through throttled_send should take about 9 seconds in total, not close to zero.
Step 4: now you own the API, so where does the limit go?
Take a fixed window of 100 requests per minute. A client sends 100 requests in the last second of one minute and 100 in the first second of the next. Both windows are within the limit, yet the backend takes 200 requests in roughly 2 seconds. A token bucket with a small capacity would not let that burst through.
That bucket belongs in the API gateway, the software layer IBM describes as a single entry point for clients reaching many backend services. Rate limiting is a job for the gateway rather than the load balancer, because the gateway is where you stop any single client or IP from overloading a service.
Placing the limit there, as Tyk recommends, lets the policy be applied consistently per API key, IP or user.
At the gateway, separate the two functions you used in Step 3. Rate limiting sets a ceiling on requests and rejects the excess; throttling slows, delays or queues requests when traffic spikes. With the same token bucket, the client side uses sleep to queue, while the server side refuses immediately.
Step 5: return 429 in a way clients can act on
Tyk notes that returning 429 is standard practice, along with headers such as Retry-After, X-RateLimit-Limit and X-RateLimit-Remaining. Your response is exactly the signal the client from Step 1 needs to read. The snippet below simulates this logic, with one bucket per API key.
buckets = {}
LIMIT = 10
def check(api_key):
b = buckets.setdefault(api_key, TokenBucket(rate=LIMIT, capacity=LIMIT))
allowed = b.take()
headers = {"X-RateLimit-Limit": str(LIMIT),
"X-RateLimit-Remaining": str(int(b.tokens))}
if not allowed:
headers["Retry-After"] = "1"
return 429, headers
return 200, headers
This is only an in-process illustration. In a real deployment, you configure this policy on the gateway the client already uses, following that product’s documentation, rather than writing it yourself. Check: call check("key-a") 15 times in a row and you should see about 5 responses of 429, while check("key-b") still returns 200.
The mistakes that get integration keys locked
A common mistake is retrying immediately on a 429. The code exists to say the client has sent too many requests, so an instant retry only piles more load onto the system that is already overloaded. The second is parsing only the numeric form of Retry-After, so the job crashes at 2am the first time it meets a date.
The third is harder to spot: running several workers in parallel, each with its own bucket set to 8 requests per second. Five workers add up to 40 requests per second, four times the ceiling. Every worker sharing a key must share a bucket.
On a client site, start with three questions
In your first session with the client’s IT team, ask three questions before writing a line of code: what the ceiling is, whether it is counted per key, IP or user, and which other applications share this key. The answers set your rate parameter.
From there, you can work out the minimum time for each job, as in the 5-minute calculation above, and tell the client in advance.
If the job description you are targeting mentions integrating with client systems, bring this very example to the interview: the quota arithmetic, the bucket shared across all workers, and how you read Retry-After.
Clients rarely remember how fast your job ran. What they remember is that, for the whole project, their system never once raised an alert because of you.
Was this article useful?
Thanks for the feedback!
9 sources
- Rate limit - Glossary | MDN · 2025-07-11
- Throttle - Glossary | MDN · 2025-07-11
- Debounce - Glossary | MDN · 2025-07-11
- 429 Too Many Requests - HTTP | MDN · 2026-06-22
- Retry-After header - HTTP | MDN · 2025-11-21
- API rate limiting explained: From basics to best practices (Tyk) · 2023-02-03
- What is an API gateway? (IBM) · 2024-08-15
- API gateway vs. Load balancer: Do you need one or both?
- Exponential Backoff And Jitter (AWS Architecture Blog) · 2015-03-04