Sessions, Queues & Counters
Session stores, job queues, delayed jobs, and real-time counters
Three more patterns that show up in almost every web backend.
Session store
A web session is small, read on every request, written often, and should disappear when the user goes idle. That's a near-perfect fit for a Redis hash with a sliding TTL:
Things to decide up front:
- Session ID: at least 128 random bits from a CSPRNG. Never a user ID or a sequential number.
- "Log out everywhere": keep a set of a user's session IDs,
SADD user:42:sessions 7f3a9c, so you can find and delete them all. (The set entries outlive expired sessions; clean them lazily.) - Durability: a failover can lose the last second of writes, which
for sessions usually means a few users get logged out. If that's
unacceptable, the session store needs
appendfsync alwaysor a database. - Eviction: sessions must not be evicted to make room for cache
entries. Use
noevictionor a separate instance from your cache.
Job queues
Three ways to build a queue in Redis, from simplest to most robust:
| Approach | Delivery | Crash safety | Multiple consumer groups |
|---|---|---|---|
List + BRPOP | Each job to one worker | Lost if a worker crashes mid-job | No |
List + BLMOVE to a processing list | Each job to one worker | Recoverable, with a reaper you write | No |
| Stream + consumer group | Each job to one worker per group | Built in: pending list + XAUTOCLAIM | Yes |
For new work, use streams. They're covered in full in Streams. Libraries like Sidekiq (Ruby), BullMQ (Node), RQ and Celery (Python) build queues on Redis and handle retries, scheduling, and dead letters for you.
Delayed jobs
A sorted set scored by run-at time:
ZADD app:jobs:delayed 1791790000 '{"type":"send_reminder","user":42}'
# a scheduler loop, every second:
ZRANGE app:jobs:delayed -inf <now> BYSCORE LIMIT 0 100 # jobs that are due
# for each: ZREM it (only the caller whose ZREM returns 1 owns the job), then enqueue itZREM returning 1 is the claim: if two scheduler processes see the same
due job, only one successfully removes it. Doing the range and the remove
in one Lua script avoids even fetching jobs another scheduler is taking.
Real-time counters
Atomic increments make Redis a natural home for live counts:
The usual pattern is count in Redis, persist periodically: a job reads and resets counters every minute and writes them to Postgres or ClickHouse, so Redis holds only the live window and the database holds history.
# move a counter to the database atomically: read and reset in one step
GETDEL app:stats:views:article:991 # returns the count and deletes the keyINCR is atomic, but "read the counter, write it to the DB, then reset
it" isn't. Increments that land between your GET and your SET 0
are lost. Use GETDEL (or GETSET key 0) so the read and the reset are
one operation, and new increments start a fresh counter.
Feature flags and config
Values every request reads, changed rarely:
HSET app:flags new_checkout on beta_search off
HGET app:flags new_checkoutAt high request rates this becomes a hot key.
Cache it in application memory for a few seconds, or use client-side
caching (CLIENT TRACKING), so each app server reads Redis once rather
than once per request.
Lab
- Implement login/logout and a sliding 30-minute session in Python with a hash, plus "log out everywhere" with a per-user set.
- Build the delayed-job scheduler: add 5 jobs due 1-5 seconds from now
and a loop that moves due jobs into
stream:jobs. - Write a view counter with
INCR, and a flush job that usesGETDELto move counts into a Python dict "database" every 5 seconds while another thread increments. Confirm no increments are lost.