In January I wrote I Replaced Redis with PostgreSQL (And It's Faster). It got 59,000 views and 46 comments, which is about 58,000 more views than I expected.
At the end I asked if you wanted a follow-up called "When Redis is Actually Better". This is it. It's ten months late.
The comments were the best part of that post, and the sharpest ones were pushback:
-
david duymelinck pointed out that my "combined operations" comparison was unfair, because Redis can batch commands in a
MULTI/EXECtransaction. Later he said, politely, that some of my replies seemed to be "cutting corners" to prove a point. He was right. - Benjamin Houdu said a fair benchmark should compare my PL/pgSQL tricks with Redis Lua scripts, and that Redis would "really outmatch" Postgres there.
- Varma Sagi wrote one line: "Sessions in db is only good for applications with low traffic." I answered "Depends." That wasn't an answer.
- PEACEBINFLOW asked for the fine print: NOTIFY delivery semantics, queue table bloat, what UNLOGGED actually means after a crash.
So this time I didn't write from memory. I ran Postgres and Redis side by side, wrote the scripts, and measured the things the first post skipped. All the scripts are included at the end, so you can run them on your own hardware and tell me where I'm wrong. Again.
How I measured
- Machine: 4 vCPU (Intel Xeon @ 2.1 GHz), 15 GB RAM, one box.
-
Versions: PostgreSQL 16.15 (
shared_buffers = 2GB, everything else default) and Redis 7.0.15 with persistence off. -
Clients:
pgbenchwith custom scripts andredis-benchmark, over local connections, on the same machine as the servers. - Data: generated by the scripts (1M cache keys, 1M leaderboard players, 10M page views).
Client and server share 4 cores, so absolute numbers are lower than on a real server. The ratios are what matter. I ran everything twice. Most results were within about 12% of each other; where the runs differed more, I show both. A newer Postgres, or Valkey 8 with its multi-threaded I/O, will move some of them.
First, the case I got backwards
I expected plain caching to be Redis's easiest win. It wasn't.
GET and SET on 1M keys with 200-byte values. Postgres uses an UNLOGGED table with a primary key, the same one from the January post.
| Plain cache, 1M keys | PostgreSQL | Redis |
|---|---|---|
| GET, 1 client | 18,300/s | 20,900/s |
| GET, 50 clients | 128,000–150,700/s | 109,400–112,500/s |
| SET, 50 clients | 66,500/s | 107,900/s |
| GET, 50 clients, pipelined (16) | n/a | 486,500/s |
With 50 clients, Postgres served more reads per second than Redis, in both runs I did. In January my decision matrix said "keep Redis if you need 100k+ ops/sec". On this box, Postgres did 128k to 150k simple reads per second. That line was wrong.
Here's the catch. I watched CPU during that run:
- Postgres: about 3.3 cores busy for 150k reads/s.
- Redis: one core (it's single-threaded) for 109k reads/s.
Per core, Redis did 2 to 2.5x the work. Postgres matched it by using the whole machine. Turn on pipelining and Redis jumps to almost half a million reads a second, still on one core.
So Varma was half right about sessions. Postgres can absolutely handle the traffic. The question is whether you want your primary database burning three cores on session lookups, while those same cores should be running your actual queries.
There's also the fine print PEACEBINFLOW asked about. An UNLOGGED table:
- is truncated after a crash or any unclean shutdown. Your cache starts cold, which is fine. If you put sessions there, every user is logged out, which might not be.
- is not replicated. If you fail over to a standby, the table is empty. If you send reads to a replica, the query fails, because replicas can't read unlogged tables.
- has no TTL. Expired rows stay until your cleanup job deletes them, and every delete leaves a dead row for autovacuum.
None of that is a dealbreaker. It's just more than the "perfect for cache!" I wrote in January.
Verdict: for a cache or sessions next to a small or medium app, Postgres is still fine. Redis wins when cache traffic is big enough that you'd rather spend one core on it than three of your primary database's.
Case 1: leaderboards and rankings (Redis wins by ~1000x)
This was the biggest gap I measured. Not 2x. Three orders of magnitude.
1M players. Three operations: show the top 10, add points to a player, and tell a player their rank ("you're #48,213").
In Postgres it's a table with an index on the score:
CREATE TABLE leaderboard (
user_id int PRIMARY KEY,
score int NOT NULL
);
CREATE INDEX lb_score ON leaderboard (score DESC);
-- top 10
SELECT user_id, score FROM leaderboard ORDER BY score DESC LIMIT 10;
-- add points
UPDATE leaderboard SET score = score + 10 WHERE user_id = $1;
-- what's my rank?
SELECT count(*) + 1 AS rank
FROM leaderboard
WHERE score > (SELECT score FROM leaderboard WHERE user_id = $1);
In Redis it's a sorted set:
ZREVRANGE lb 0 9 WITHSCORES
ZINCRBY lb 10 member:42
ZREVRANK lb member:42
16 clients, random players:
| Leaderboard, 1M players | PostgreSQL | Redis |
|---|---|---|
| Top 10 | 151,700/s | 74,000/s |
| Add points | 19,400/s | 57,100/s |
| Rank of one player | 62/s (259 ms avg) | 62,400/s |
The top 10 is fast in Postgres because it reads 10 entries off the index. Rank is the problem. To know you're #500,000, Postgres has to count the 499,999 rows above you. It's O(rank), and it gets slower as your table grows. A single rank lookup for a player in the middle took about 45 ms, even with two parallel workers.
A Redis sorted set is a skip list that tracks how many elements each link jumps over, so rank is O(log N). With 1M players that's about 20 steps instead of 500,000.
Can you fix it in Postgres? Partly. You can precompute ranks in a materialized view and refresh it every minute, or bucket scores into a histogram table. Both work, and both mean your ranks are a little stale and you now own a refresh job. If "your rank" is on every profile page and updates live, use a sorted set.
The same goes for anything that's "position in an ordered set that changes all the time": trending lists, priority queues with re-scoring, "N people ahead of you" waitlists.
Case 2: rate limiting that's both precise and correct (Redis wins ~3x, and it's atomic)
In January I showed a sliding-window rate limiter in Postgres: insert the request, count the requests in the last minute. I measured it against the usual Redis version, a Lua script on a sorted set:
-- rl_sliding.lua: sliding 60s window, one sorted set per user
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - 60000)
redis.call('ZADD', KEYS[1], now, t[1] .. t[2] .. math.random())
redis.call('PEXPIRE', KEYS[1], 60000)
return redis.call('ZCARD', KEYS[1])
10,000 users, 16 clients:
| Sliding window, 10k users | PostgreSQL | Redis (Lua) |
|---|---|---|
| Checks per second | 14,200/s | 45,400/s |
| Leftovers after 90 s | 1.27M rows, 106 MB | keys expire by themselves |
3x is not dramatic. Two other things are.
Storage. In 90 seconds the Postgres table grew to 106 MB, because nothing deletes old requests unless you schedule a job for it. Redis deletes old entries inside the script, and PEXPIRE drops the whole key once a user goes quiet. You can switch Postgres to a fixed-window counter with UPDATE ... SET count = count + 1 to avoid the table growth, though you still pay for row locks and autovacuum churn on hot user keys, and you lose the sliding window.
Correctness. Insert-then-count is racy. Two requests from the same user arrive together, both count 99, both get in. To fix it you need a row lock or an advisory lock per user, which makes it slower. The Lua script runs atomically by design. That's the point Benjamin made in the comments, and he was right.
If you rate limit in front of an API that thousands of clients hit, Redis is the better tool. If you rate limit "max 5 exports per hour" inside business logic, Postgres is still fine, and you get to do it in the same transaction as the export.
Case 3: counting unique things (Redis wins on memory, by a lot)
"How many unique visitors this week?" In SQL it's COUNT(DISTINCT). In Redis it's a HyperLogLog.
10M page views, about 2.9M unique visitors:
| Unique visitors | PostgreSQL COUNT(DISTINCT)
|
Redis HyperLogLog |
|---|---|---|
| Storage | 346 MB table | 12 KB |
| Time to answer | 3.4 s | 0.09 ms |
| Accuracy | exact (2,892,552) | 0.6–1% off across runs |
HyperLogLog trades exactness for size: 12 KB per counter, no matter how many items you add, with about 0.8% standard error. One counter per page per day is cheap. You can merge them with PFMERGE to get the week.
Postgres has an answer here, the hll extension, and it works well. But it's an extension: some managed Postgres offerings don't ship it, and on those that do you manage binary hll columns and merge functions yourself. Redis has it built in.
To be fair, the 346 MB is the raw events table, which you'd likely keep anyway. The point is that an exact answer has to scan it, or a table of distinct IDs, every time, while the HyperLogLog answers from 12 KB.
If you need exact counts for billing, use Postgres. For dashboards, use an approximation, wherever it runs.
Case 4: queues with real volume (Redis wins 10x+, and Postgres has a failure mode)
I still run a Postgres queue. LogTide's simple deployment uses graphile-worker, and I wrote a whole post about why. But there's one thing I didn't tell you in January.
Queues in Postgres slow down over time
Each job is an insert and then a delete. Every delete leaves a dead row behind, and the index keeps pointing at it until autovacuum cleans up. The workers all read from the head of the index, which is exactly where the dead rows pile up.
16 workers, each transaction enqueues one job and dequeues one, 10k jobs in backlog:
progress: 30 s, 4959 tps
progress: 60 s, 3443 tps
progress: 90 s, 4627 tps <- autovacuum just ran
progress: 120 s, 3145 tps
...
average over 4 minutes: 3,922 tps
That sawtooth is autovacuum catching up and falling behind. It's fine. Now the bad version: I opened one other session, started a REPEATABLE READ transaction, ran a SELECT, and left it open. That's what a stuck report query, a forgotten psql session, or a long backup looks like. Vacuum can't remove any row that transaction might still see.
progress: 10 s, 1329 tps
progress: 30 s, 630 tps
progress: 60 s, 404 tps
progress: 90 s, 349 tps
progress: 120 s, 295 tps <- and still falling
dead rows in the jobs table: 61,219
A 13x drop in two minutes, caused by a session that wasn't even touching the queue. In production that shows up as "jobs are late" while every queue metric looks normal. Watch pg_stat_activity for old xact_start, and set idle_in_transaction_session_timeout.
Redis LPUSH/RPOP on the same machine: about 92,000 per second each way, so roughly 45,000 enqueue-plus-dequeue pairs per second against Postgres's 3,900. No vacuum, and no other session can slow it down.
Verdict: a few hundred jobs per second, and you want them in the same transaction as your data? Postgres. Thousands per second, or a database shared with long analytical queries? Use Redis (BullMQ) or a real broker.
Case 5: pub/sub with many writers or many listeners
I love LISTEN/NOTIFY. LogTide's live tail is built on it, and I wrote a post about that too. It has two limits I didn't mention in January.
NOTIFY serializes your commits
When a transaction that called NOTIFY commits, Postgres takes a single global lock to append to the notification queue, so that notifications come out in commit order. Every writer that notifies waits in the same line.
32 clients, each transaction inserts one row:
| 32 concurrent writers | Transactions/s |
|---|---|
INSERT in a transaction |
16,600 |
Same transaction + pg_notify()
|
3,900 |
Redis PUBLISH (for reference) |
117,500 |
Adding one pg_notify call cut write throughput by 4.2x. This measures publisher commit throughput, not end-to-end delivery latency: the listener in the test is connected but idle, and the bottleneck is the lock at commit, not the delivery. A trigger that calls pg_notify for every inserted row is the pattern that hurts most under load. Notify once per batch, or send only "something changed" and let listeners query for new rows.
Every listener is a Postgres connection
Every LISTEN holds a connection, and in Postgres every connection is a process. I opened 1,000 idle listeners:
- Postgres: 1,000 backends, about 1.2 GB of memory (roughly 1.2 MB each, while idle).
- Redis: 10,000 subscribers, between 59 and 134 MB of client memory across two runs (6 to 14 KB each).
And you can't put PgBouncer in transaction mode in front of LISTEN, because the listening session has to stay on one server connection. (Here's why connection count matters so much in Postgres.)
Delivery semantics matter too. NOTIFY is fire-and-forget: a listener that's disconnected at that moment never gets the message, and payloads must be under 8,000 bytes. Redis Pub/Sub is also fire-and-forget, but Redis Streams give you consumer groups, acknowledgements, and replay, which is a different league.
Verdict: a handful of backend processes listening for "new data" signals? LISTEN/NOTIFY is perfect. Thousands of browser connections, a chat, or a stream you need to replay? Redis.
About the "combined operations" comparison
This is david's point from January. I compared a Postgres transaction (insert, delete the cache row, notify, about 2.2 ms) with three separate Redis calls (about 4 ms) and called Postgres faster.
With MULTI/EXEC or a pipeline, those Redis calls go out in one round trip, so most of the gap goes away. What's left is the real argument: the Postgres version is atomic with your data, and the Redis version is a second system that can fail on its own. That argument still holds. "Faster" was the wrong word.
What happened in LogTide
After the January post I didn't remove Redis from LogTide. I made it optional (here's how):
-
docker-compose.simple.yml: Postgres only. graphile-worker for jobs, UNLOGGED tables for cache, LISTEN/NOTIFY for live tail. -
docker-compose.yml: Postgres plus Redis or Valkey, with BullMQ for jobs, for people running several backend instances.
Back then I measured 10,000 background jobs: 2,050 ms on Postgres, 770 ms on Valkey. For log rotation and alert checks, that difference doesn't matter.
If you run the simple setup, the NOTIFY numbers above are the ones to keep an eye on. Live tail sits on LISTEN/NOTIFY, so on a busy instance it's worth notifying once per batch of logs, not once per row.
The way I'd put it now: Postgres is the default, Redis is an upgrade you buy when one of the cases above shows up. It isn't a mistake to remove Redis, and it isn't a mistake to keep it.
The updated decision matrix
What changed since January:
| January | Now | |
|---|---|---|
| Plain cache / sessions | Keep Redis at 100k+ ops/s | Postgres handled 128k–150k reads/s here. Redis wins on CPU per request, not raw throughput |
| Sorted sets / rankings | "Clunkier" in Postgres | ~1000x gap for rank lookups. Use Redis |
| Rate limiting | Postgres OK unless millions/s | Redis is ~3x faster, atomic, and cleans up after itself |
| Unique counts | Not covered | HyperLogLog: 12 KB vs 346 MB. Redis, or the hll extension |
| Job queues | SKIP LOCKED is enough | Fine up to hundreds/s. Long transactions can stall it. |
| Pub/sub | NOTIFY is "slightly slower" | NOTIFY serializes commits (4.2x drop with 32 writers) and costs a process per listener |
| Combined operations | "Postgres is faster" | Postgres is atomic. Not necessarily faster |
Stay on Postgres if:
- cache and sessions are for one app, at the scale of one app
- jobs run in the hundreds per second and you want them in the same transaction as your data
- pub/sub is a few backend listeners getting "something changed" signals
- you'd rather run one database well than two databases okay
Bring Redis (or Valkey) back if:
- you need rank, "top N", or anything re-sorted all the time
- you rate limit at the edge, at high volume
- you count unique things for dashboards
- you push messages to thousands of connected clients, or need replay (Streams)
- your queue does thousands of jobs per second, or shares a database with long-running queries
- your primary database's CPU is precious and cache traffic is eating it
TL;DR
- Postgres is better at plain caching than I said in January. It just spends more CPU doing it.
- Redis is far better than I said at rankings (~1000x), unique counts (12 KB vs 346 MB), and fan-out to many listeners (under 15 KB vs ~1.2 MB per connection).
-
LISTEN/NOTIFYserializes commits. 32 writers lost 76% of their throughput. - A Postgres queue can be stalled by a transaction that never touches it.
- Postgres-first is still my default. It's a default, not a religion.
Everything above comes from one script. You need a throwaway Postgres (max_connections of at least 1100 for the listener test, otherwise the script skips it), a throwaway Redis or Valkey, and about 15 minutes. Save the files below in one folder and run ./run.sh.
run.sh (click to expand)
#!/usr/bin/env bash
# Benchmarks for "When Redis Is Actually Better Than PostgreSQL".
# Needs: a throwaway PostgreSQL (psql + pgbench) and a throwaway Redis/Valkey (redis-cli + redis-benchmark), python3.
# Everything it creates is dropped/overwritten. Do NOT point it at a real database.
#
# PGHOST=/tmp PGPORT=5433 PGUSER=postgres REDIS_PORT=6380 ./run.sh
#
# Postgres needs max_connections >= 1100 for the LISTEN test.
set -euo pipefail
cd "$(dirname "$0")"
: "${PGHOST:=/tmp}" "${PGPORT:=5432}" "${PGUSER:=postgres}" "${PGDATABASE:=postgres}"
: "${REDIS_HOST:=127.0.0.1}" "${REDIS_PORT:=6379}"
: "${T:=20}" # seconds per pgbench run
export PGHOST PGPORT PGUSER PGDATABASE REDIS_HOST REDIS_PORT
P="psql -q -v ON_ERROR_STOP=1"
R="redis-cli -h $REDIS_HOST -p $REDIS_PORT"
pgb() { pgbench -n -M prepared "$@" 2>&1 | grep -E "^tps|latency average|^progress" ; }
rb() { redis-benchmark -h "$REDIS_HOST" -p "$REDIS_PORT" --threads 4 -q "$@" 2>/dev/null | tr '\r' '\n' | grep "per second"; }
echo "## Versions"; $P -Atc "select version()"; $R info server | grep -E "^(redis|valkey)_version"
echo "nproc=$(nproc)"; grep -m1 "model name" /proc/cpuinfo || true
echo; echo "## 1. Plain key-value cache (1M keys, 200-byte values)"
$P -c "DROP TABLE IF EXISTS cache" \
-c "CREATE UNLOGGED TABLE cache (key text PRIMARY KEY, value text NOT NULL, expires_at timestamptz NOT NULL)" \
-c "INSERT INTO cache SELECT 'key:'||g, repeat('x',200), now()+interval '1 hour' FROM generate_series(1,1000000) g" \
-c "VACUUM ANALYZE cache"
for c in 1 50; do
for f in cache_get cache_set; do echo "PG $f clients=$c"; pgb -c $c -j 4 -T $T -f $f.sql; done
echo "Redis clients=$c"; rb -c $c -n $((c==1 ? 200000 : 2000000)) -r 1000000 -d 200 -t set,get
done
echo "Redis pipelined (-P 16)"; rb -c 50 -n 5000000 -r 1000000 -d 200 -t set,get -P 16
echo; echo "## 2. Job queue: enqueue + SKIP LOCKED dequeue, 16 workers"
$P -c "DROP TABLE IF EXISTS jobs" \
-c "CREATE TABLE jobs (id bigserial PRIMARY KEY, queue text NOT NULL, payload jsonb NOT NULL, run_at timestamptz NOT NULL DEFAULT now())" \
-c "CREATE INDEX jobs_q ON jobs (queue, run_at)" \
-c "INSERT INTO jobs (queue,payload) SELECT 'default', '{\"n\":1}' FROM generate_series(1,10000)" \
-c "VACUUM ANALYZE jobs"
echo "PG baseline (240s, watch the autovacuum sawtooth)"; pgb -c 16 -j 4 -T 240 -P 30 -f queue.sql
echo "PG with one forgotten REPEATABLE READ transaction (120s)"
$P -c "VACUUM jobs"
psql -c "BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM jobs; SELECT pg_sleep(150);" >/dev/null 2>&1 &
sleep 1; pgb -c 16 -j 4 -T 120 -P 10 -f queue.sql
$P -Atc "SELECT 'live='||n_live_tup||' dead='||n_dead_tup FROM pg_stat_user_tables WHERE relname='jobs'"
$P -Atc "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query LIKE '%pg_sleep(150)%' AND pid<>pg_backend_pid()" >/dev/null
echo "Redis LPUSH/RPOP"; rb -c 16 -n 2000000 -t lpush,rpop
echo; echo "## 3. Leaderboard, 1M players"
$P -c "DROP TABLE IF EXISTS leaderboard" \
-c "CREATE TABLE leaderboard (user_id int PRIMARY KEY, score int NOT NULL)" \
-c "INSERT INTO leaderboard SELECT g, (random()*1000000)::int FROM generate_series(1,1000000) g" \
-c "CREATE INDEX lb_score ON leaderboard (score DESC)" -c "VACUUM ANALYZE leaderboard"
for f in lb_top lb_incr lb_rank; do echo "PG $f"; pgb -c 16 -j 4 -T $T -f $f.sql; done
$R del lb >/dev/null
python3 -I -c "
import random
for i in range(1,1000001): print(f'ZADD lb {random.randint(0,1000000)} member:{i:012d}')" | $R --pipe | tail -1
rb -c 16 -n 500000 -r 1000000 ZREVRANGE lb 0 9 WITHSCORES
rb -c 16 -n 500000 -r 1000000 ZINCRBY lb 10 member:__rand_int__
rb -c 16 -n 500000 -r 1000000 ZREVRANK lb member:__rand_int__
echo; echo "## 4. Sliding-window rate limit, 10k users"
$P -c "DROP TABLE IF EXISTS api_requests" \
-c "CREATE TABLE api_requests (user_id int NOT NULL, created_at timestamptz NOT NULL DEFAULT now())" \
-c "CREATE INDEX ON api_requests (user_id, created_at)"
echo "PG insert + count (90s, no cleanup job)"; pgb -c 16 -j 4 -T 90 -P 30 -f rl_sliding.sql
$P -Atc "SELECT count(*)||' rows, '||pg_size_pretty(pg_total_relation_size('api_requests')) FROM api_requests"
SHA=$($R script load "$(cat rl_sliding.lua)")
echo "Redis Lua sorted-set window"; rb -c 16 -n 1000000 -r 10000 EVALSHA "$SHA" 1 rl:__rand_int__
echo; echo "## 5. LISTEN/NOTIFY under concurrent writers (32 clients)"
$P -c "DROP TABLE IF EXISTS events" -c "CREATE TABLE events (id bigserial PRIMARY KEY, body text)"
psql -c "LISTEN events; SELECT pg_sleep(60);" >/dev/null 2>&1 &
sleep 1
echo "PG insert in a transaction"; pgb -c 32 -j 4 -T $T -f ins_tx.sql
echo "PG same transaction + pg_notify"; pgb -c 32 -j 4 -T $T -f ins_notify.sql
echo "Redis PUBLISH"; rb -c 32 -n 1000000 PUBLISH events hello
$P -Atc "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query LIKE '%pg_sleep(60)%' AND pid<>pg_backend_pid()" >/dev/null
echo; echo "## 6. Memory for 1000 idle LISTEN connections vs Redis subscribers"
MAXC=$(psql -Atc "SHOW max_connections")
if [ "$MAXC" -lt 1100 ]; then
echo "Skipping the Postgres half of test 6: max_connections=$MAXC, it needs >= 1100 (set it and restart Postgres)."
else
pgbench -n -c 1000 -j 4 -t 1 -f listen_hold.sql >/dev/null 2>&1 &
sleep 25
python3 -I pg_backend_mem.py # needs the Postgres server on this machine
wait || true
fi
python3 -I redis_subs.py 1000
python3 -I redis_subs.py 10000
echo; echo "## 7. Unique visitors: COUNT(DISTINCT) vs HyperLogLog (10M events, ~2.9M uniques)"
$P -c "DROP TABLE IF EXISTS page_views" \
-c "CREATE TABLE page_views (visitor_id bigint NOT NULL)" \
-c "INSERT INTO page_views SELECT (random()*3000000)::bigint FROM generate_series(1,10000000)" \
-c "VACUUM ANALYZE page_views"
$P -Atc "SELECT 'table size '||pg_size_pretty(pg_total_relation_size('page_views'))"
psql -c '\timing on' -c "SELECT count(DISTINCT visitor_id) FROM page_views" | grep -E "Time|^ +[0-9]"
$R del hll >/dev/null
python3 -I -c "
import random
for b in range(10000):
print('PFADD hll ' + ' '.join(str(int(random.random()*3000000)) for _ in range(1000)))" | $R --pipe | tail -1
echo "PFCOUNT=$($R pfcount hll) bytes=$($R strlen hll)"
rb -c 16 -n 200000 PFCOUNT hll
The pgbench scripts, Lua and Python helpers (click to expand)
cache_get.sql
\set k random(1, 1000000)
SELECT value FROM cache WHERE key = 'key:' || :k AND expires_at > now();
cache_set.sql
\set k random(1, 1000000)
INSERT INTO cache (key, value, expires_at) VALUES ('key:' || :k, repeat('y',200), now() + interval '1 hour')
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at;
ins_notify.sql
BEGIN;
INSERT INTO events (body) VALUES ('hello');
SELECT pg_notify('events', 'hello');
COMMIT;
ins_tx.sql
BEGIN;
INSERT INTO events (body) VALUES ('hello');
SELECT 1;
COMMIT;
lb_incr.sql
\set u random(1, 1000000)
UPDATE leaderboard SET score = score + 10 WHERE user_id = :u;
lb_rank.sql
\set u random(1, 1000000)
SELECT count(*) + 1 AS rank FROM leaderboard
WHERE score > (SELECT score FROM leaderboard WHERE user_id = :u);
lb_top.sql
SELECT user_id, score FROM leaderboard ORDER BY score DESC LIMIT 10;
listen_hold.sql
LISTEN events;
SELECT pg_sleep(40);
queue.sql
INSERT INTO jobs (queue, payload) VALUES ('default', '{"to":"user@example.com"}');
WITH next AS (
SELECT id FROM jobs WHERE queue = 'default' AND run_at <= now()
ORDER BY run_at LIMIT 1 FOR UPDATE SKIP LOCKED)
DELETE FROM jobs USING next WHERE jobs.id = next.id RETURNING jobs.id;
pg_backend_mem.py
# Sums the memory (PSS) of local Postgres client backends. Postgres must run on this machine.
import os
tot = n = 0
for p in filter(str.isdigit, os.listdir('/proc')):
try:
cmd = open(f'/proc/{p}/cmdline', 'rb').read()
if b'postgres:' in cmd and (b'idle' in cmd or b'SELECT' in cmd or b'LISTEN' in cmd):
for l in open(f'/proc/{p}/smaps_rollup'):
if l.startswith('Pss:'): tot += int(l.split()[1]); n += 1
except Exception: pass
print(f"PG client backends={n} total PSS={tot/1024:.0f} MB (~{tot/max(n,1):.0f} kB each)")
redis_subs.py
# Opens N subscriber connections to Redis/Valkey and reports client memory.
import os, socket, subprocess, sys, time
host = os.environ.get('REDIS_HOST', '127.0.0.1'); port = os.environ.get('REDIS_PORT', '6379')
cli = ['redis-cli', '-h', host, '-p', port]
N = int(sys.argv[1]); socks = []
for _ in range(N):
s = socket.create_connection((host, int(port))); s.sendall(b'SUBSCRIBE events\r\n'); socks.append(s)
time.sleep(2)
info = subprocess.check_output(cli + ['info']).decode()
get = lambda k: [l.split(':')[1].strip() for l in info.splitlines() if l.startswith(k + ':')][0]
mem = int(get('mem_clients_normal'))
print(f"Redis subscribers={N} connected_clients={get('connected_clients')} client memory={mem/1048576:.0f} MB (~{mem/N/1024:.1f} kB each)")
rl_sliding.lua
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - 60000)
redis.call('ZADD', KEYS[1], now, t[1] .. t[2] .. math.random())
redis.call('PEXPIRE', KEYS[1], 60000)
return redis.call('ZCARD', KEYS[1])
rl_sliding.sql
\set u random(1, 10000)
INSERT INTO api_requests (user_id) VALUES (:u);
SELECT count(*) FROM api_requests WHERE user_id = :u AND created_at > now() - interval '1 minute';
If your numbers look different, especially on Valkey 8 or Postgres 18, post them in the comments.
Have you gone back to Redis after removing it? What was the thing that made you do it?
Top comments (0)