Menu

1 / 5

LRU Cache and Rate Limiter: Two Small Designs That Protect an API

DEV Community: gcp·Vishwa·4 days ago
#iGmN7HDY
#devtogcp#devto#dev#self#cache
Long article (1136 words) — no AI summary yet.
Reading 0:00
15s threshold

How I would stop one user from calling an API 1,000 times a minute, with Python you can run

Imagine a link-shortening service. A script starts calling POST /shorten in a loop, say 1,000 times a minute from one API key. At the same moment, real users are opening product pages that read the same few items again and again.

Two small designs handle both problems: a rate limiter that says "enough" to the noisy caller, and an LRU cache that keeps the hot data close and throws out what nobody is reading.

The problem

Without a limit, one client can use up the capacity meant for everyone. The database fills with junk rows, latency climbs, and real users start seeing errors they did nothing to cause.

Without a sensible cache, every read goes to the database. And a cache with no size limit is not a fix either: memory is fixed, so something has to decide what leaves when it is full.

The solution, part 1: the rate limiter

A rate limit is the maximum number of requests allowed per user or key in a time window.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.