-- Index justification for messages (chat_id, created_at, id). -- Fixtures are deterministic and synthetic; re-running changes nothing. \set ON_ERROR_STOP on \timing on INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ('11111111-1111-4111-8111-111111111111', 'seed_user', 'Seed User', 'not-a-usable-hash', now()) ON CONFLICT (id) DO NOTHING; INSERT INTO chats (id, title, created_at) VALUES ('22222222-2222-4222-8222-222222222222', 'Seed history', now()) ON CONFLICT (id) DO NOTHING; INSERT INTO chat_members (chat_id, user_id, joined_at) VALUES ('22222222-2222-4222-8222-222222222222', '11111111-1111-4111-8111-111111111111', now()) ON CONFLICT DO NOTHING; DO $$ BEGIN IF (SELECT count(*) FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222') = 0 THEN INSERT INTO messages (id, chat_id, sender_id, text, created_at) SELECT gen_random_uuid(), '22222222-2222-4222-8222-222222222222', '11111111-1111-4111-8111-111111111111', 'seed message ' || g, timestamptz '2026-01-01 00:00:00+00' + make_interval(secs => g * 0.001) FROM generate_series(1, 12000) AS g; END IF; END $$; ANALYZE messages; \echo '=== dataset ===' SELECT count(*) AS messages_in_chat FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222'; \echo '=== index used by the history query ===' SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'messages'; \echo '=== plan: first page (no cursor) ===' EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222' ORDER BY created_at, id LIMIT 50; -- Pick the 10 001st record as the cursor of a deep page. SELECT created_at AS cursor_ts, id AS cursor_id FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222' ORDER BY created_at, id OFFSET 10000 LIMIT 1 \gset \echo '=== plan: deep keyset page after 10 000 records (what the API sends) ===' EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222' AND (created_at, id) > (:'cursor_ts'::timestamptz, :'cursor_id'::uuid) ORDER BY created_at, id LIMIT 50; \echo '=== comparison: the OFFSET form this API does not use ===' EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222' ORDER BY created_at, id OFFSET 10000 LIMIT 50;