Concurrent session limits and 'log out everywhere' done right
Capping how many sessions a user can hold at once, and offering a clean "log out everywhere," sound like afternoon features. They stay that simple right up until you remember that modern auth runs on stateless access tokens, long-lived refresh tokens, and caches spread across several services. Suddenly "end all sessions" means revoking things that were designed never to need revoking, and "only three devices" means coordinating a count across machines that do not share memory.
The reason these features are hard is the same reason JWTs scale: a signed access token is valid because the signature checks out, not because a server looked it up. If nobody looks it up, nobody can turn it off. Getting concurrent limits and global logout right is really about deciding where you reintroduce server-side state, and keeping that state cheap.
You need a server-side session record
If your access tokens are opaque and checked against a store on every request, revocation is trivial: delete the row. The hard case is JWTs, and the fix is to stop treating the refresh token as fire-and-forget. Every session gets a durable record keyed by a session ID that you embed in both the access and refresh tokens.
CREATE TABLE sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
device_label TEXT,
ip INET,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_used_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ
);
CREATE INDEX idx_sessions_active ON sessions(user_id)
WHERE revoked_at IS NULL;
The access token still carries claims and is still verified by signature, but it also carries sid. Revocation now means setting revoked_at on the session, and refresh requests for a revoked session are denied. The only thing left to solve is the window between access-token issuance and expiry.
The access-token window is the whole trick
A revoked session should not keep working for the full lifetime of an already-issued access token. You have two levers, and most robust systems use both.
Keep access tokens short
If access tokens live 5 to 15 minutes, the worst-case exposure after revocation is that short window, because the refresh that would extend the session is blocked. For many applications this is good enough and requires zero per-request lookups.
Add a revocation check for sensitive paths
For high-value operations you cannot tolerate even a 10-minute window, so check the sid against a fast store on those routes. A denylist of revoked session IDs in an in-memory cache keeps this cheap.
// Fast revocation check backed by Redis, only on sensitive routes.
async function assertSessionLive(sid: string): Promise<void> {
// Each revoked sid is its own key with a TTL, so expired entries vanish.
const revoked = await redis.exists(`rev:${sid}`);
if (revoked) throw new UnauthorizedError("session_revoked");
}
// On "log out everywhere": revoke in the DB and publish to the cache.
async function logoutEverywhere(userId: string): Promise<void> {
const sids = await db.sessions.revokeAllActive(userId); // sets revoked_at
// One key per revoked sid, each with a TTL of the access-token lifetime
// (900s) so the denylist self-trims once those tokens would have expired.
await Promise.all(sids.map(s => redis.set(`rev:${s}`, "1", "EX", 900)));
}
Rule of thumb: size the revocation denylist to the access-token lifetime, not forever. Once every access token issued before revocation has expired, the entry can disappear. Short tokens keep the set small enough to fit in memory even for large user bases.
Enforcing a concurrent-session cap
A limit like "at most five active sessions" is enforced at login, inside a transaction, by counting active sessions and deciding what gives. The policy choice is which session loses: the oldest (sliding window) or the new one (hard cap). For most products, evicting the oldest is the right default because it matches user expectation: your newest device works, your most forgotten one drops.
-- At login, atomically evict the oldest if over the cap, then insert.
WITH active AS (
SELECT id FROM sessions
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > now()
ORDER BY last_used_at DESC
),
to_revoke AS (
SELECT id FROM active OFFSET 4 -- keep newest 4, this login makes 5
)
UPDATE sessions SET revoked_at = now()
WHERE id IN (SELECT id FROM to_revoke);
Do the count-and-evict and the insert in one transaction, or two devices logging in at the same instant can both pass the check and push you over the cap. The index on active sessions keeps the count fast even for noisy accounts.
Gotcha: distributed caches are the classic correctness trap here. If one node revokes a session but the denylist propagation to other nodes lags, a request hitting a stale node still succeeds. Treat the database as the source of truth, the cache as an optimization, and make sensitive operations fall back to the DB on a cache miss rather than failing open.
Give users visibility and a kill switch
Expose the active sessions in account settings, each with a device label, location, last-used time, and an individual "sign out." Add the global "sign out of all devices" that calls the revoke-all path. This is both a usability win and a security control: it is how a user responds to a lost laptop or a suspected compromise without waiting on support.
- Per-session logout for the "I left myself logged in at a library" case.
- Global logout for the "my password may be compromised" case, ideally paired with a forced password or passkey re-enrollment.
- Automatic global revocation on password change, MFA reset, or detected takeover.
Where the state lives is your call
Concurrent limits and global logout force a deliberate decision about how much server-side session state you are willing to keep, and that decision is yours to make based on your own latency budget and threat model. Short access tokens plus a lean, TTL'd revocation set covers most applications; a full opaque-token store covers the strictest. Either way, the capability depends on owning the session layer end to end. When your identity platform is self-hosted, you can tune token lifetimes, caps, and revocation propagation to your infrastructure instead of living inside someone else's fixed defaults.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.