July 5, 2026 · 2 min read
Wiring a Live Visitor Counter with Redis
Showing how many people are viewing this portfolio in real time, using Upstash Redis and a simple heartbeat pattern — no WebSockets required.
I wanted a small "N people viewing now" indicator on this site — mostly because it's a fun, tangible way to show the portfolio is actually alive, not a static page someone deployed once and forgot about.
Why not WebSockets
The "correct" way to do real-time presence is usually a persistent WebSocket connection — the server holds a connection open per visitor and pushes updates instantly. The problem: this site is deployed on Vercel's free Hobby tier, which runs on serverless functions. Serverless functions spin up, do their job, and shut down — they're not built to hold a connection open for minutes at a time. Getting real WebSockets working would mean a separate always-on service, which defeats the "keep this free and simple" goal.
The heartbeat pattern instead
Instead of a persistent connection, each visitor's browser just pings an API route every 8 seconds: "I'm still here." Anyone who closes the tab simply stops pinging and naturally falls out of the count after a short window — no explicit "disconnect" event needed.
setInterval(() => {
fetch("/api/presence", {
method: "POST",
body: JSON.stringify({ visitorId }),
});
}, 8000);
Each visitor gets a random ID generated once and stored in sessionStorage, so it's per-tab, not tracked across sessions or devices.
Redis sorted sets are a perfect fit here
On the server side, I store each heartbeat in a single Redis sorted set — the "score" is just the last-seen timestamp, and the "member" is the visitor's ID:
await redis.zadd(PRESENCE_KEY, { score: Date.now(), member: visitorId });
Every time a new heartbeat comes in, I also sweep out anyone who's gone stale (no ping in the last 20 seconds):
await redis.zremrangebyscore(PRESENCE_KEY, 0, Date.now() - 20_000);
Then ZCARD gives me the live count in one call. No cron job, no background worker — the cleanup happens automatically as a side effect of normal traffic.
Honest limitations
This counts active browser tabs, not unique humans — two tabs from the same person count as two. And it updates every ~8 seconds, not instantly, since it's polling rather than push-based. For a personal portfolio, that trade-off is completely fine — the goal was never precise analytics, just a small sign of life on the page.