PostgreSQL and Redis: The Data Foundation of an AI App Backend
Core concepts
| Component | Role in an AI app |
|---|---|
| PostgreSQL | Business data (tasks, steps, review records), LLM call logs, vectors (pgvector), full-text search |
| JSONB | Stores LLM structured output and raw responses, with indexing and querying |
| Redis | Caching, distributed locks, rate-limit counters, task queue broker (Celery / arq), Pub/Sub for progress updates |
How it works
PostgreSQL
- MVCC: reads don't block writes and writes don't block reads; the default isolation level is Read Committed.
- Indexes: B-tree (equality/range), GIN (JSONB, full text, arrays), HNSW/IVFFlat (pgvector). Use
EXPLAIN ANALYZEto see the actual execution plan. SELECT ... FOR UPDATE SKIP LOCKED: lets several workers "grab tasks" from the same table without blocking each other; the classic way to build a simple task queue on Postgres.- Idempotency via unique constraints: a given idempotency key can be inserted only once.
Redis
- Commands execute on a single thread (I/O can be multithreaded), so a single command is atomic; use a Lua script or a transaction to make multi-step operations atomic.
- Distributed lock:
SET key value NX PX 30000; on release, check that the value is yours (Lua script). - Persistence: RDB snapshots / AOF log. When Redis is your queue broker, mind the persistence settings or a restart loses tasks.
In practice
Task table + grabbing tasks
sql
CREATE TABLE task (
id bigserial PRIMARY KEY,
idempotency_key text UNIQUE, -- duplicate external submissions create only one task
status text NOT NULL DEFAULT 'queued',
current_step text,
payload jsonb NOT NULL,
result jsonb,
attempts int NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON task (status, updated_at);
-- a worker claims one task
UPDATE task SET status = 'running', attempts = attempts + 1, updated_at = now()
WHERE id = (
SELECT id FROM task WHERE status = 'queued'
ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1
) RETURNING *;Redis fixed-window rate limiting (60 requests per customer per minute)
python
key = f"rl:{tenant_id}:{int(time.time() // 60)}"
n = await redis.incr(key)
if n == 1:
await redis.expire(key, 60)
if n > 60:
raise BizError("RATE_LIMITED", "Too many requests", 429)Common pitfalls
- Frequent updates to large JSONB: each update rewrites the whole row and log tables bloat. Large raw responses can go to object storage with only a reference stored.
- Connection count explosion: workers × pool size exceeds the database limit. Add PgBouncer if needed.
- Redis locks with no expiry, or releasing someone else's lock.
- Cache and database out of sync: on update, write the database first and then delete the cache, and set a sensible TTL.
Common interview questions
- How do you build a reliable task queue on PostgreSQL? What does
SKIP LOCKEDdo? - What is MVCC? What anomalies can occur under Read Committed?
- What is JSONB good for storing? How do you index it?
- How do you implement a Redis distributed lock? What are the pitfalls?
- What rate-limiting algorithms are there? (Fixed window, sliding window, token bucket)
