Skip to content

Latest commit

Β 

History

History

queue-based-site-access

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

README.md

🚦 Queue-Based Site Access

A production-style virtual waiting room built with Go, Redis, and Docker. Users must pass through a queue before they can reach the protected page β€” bypassing it is architecturally impossible.


Protected page Queue β€” position 1 Queue β€” position 2
Protected page Queue position 1 Queue position 2
Admitted users land on the protected page with a live "Access granted" indicator First in line β€” position counter and progress bar update every 2 s Further back in the queue β€” ETA shown once enough admission history is collected

✨ What it does

Scenario Behaviour
Capacity is available User lands directly on the protected page
Capacity is full User is placed in a FIFO queue and sees their live position
A slot opens up The next person in line is admitted automatically
User tries to access the target URL directly Redirected into the queue β€” no way around it

The waiting room page updates every 2 seconds and shows an estimated wait time once enough admission history has been collected.


πŸ—οΈ Architecture

Browser  ──►  :80
               β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€-┐
        β”‚     queue-service (Go)   │◄──► Redis
        β”‚                          β”‚
        β”‚  β€’ session gating        β”‚
        β”‚  β€’ queue management      β”‚
        β”‚  β€’ reverse proxy         β”‚
        β”‚  β€’ admin API             β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚  internal network only
        β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚   target (Nginx)        β”‚  ← no published port
        β”‚   protected page        β”‚    a browser can never
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    reach this directly
Container Tech Role
queue-service Go Session gating, queue logic, reverse proxy, admin API
target Nginx Serves the protected page β€” internal only
redis Redis 7 Stores sessions, queue list, active set, timing history

Why can't users bypass the queue? The target container has no ports: entry in compose.yml. There is no TCP path from the browser to it β€” every request must go through queue-service.


πŸš€ Quick start

make demo

Then open http://localhost in several browser tabs or incognito windows. The first 3 sessions (default capacity) land on the protected page β€” the rest land in the queue.


πŸ› οΈ Make targets

Lifecycle

make up       # Build images and start all services
make demo     # Same as up, plus a step-by-step walkthrough
make down     # Stop and remove all containers
make logs     # Follow live logs (Ctrl+C to stop)
make ps       # Show container status
make clean    # Stop containers and remove locally built images

Admin

make admin-status          # Show live queue state
make admin-capacity N=5    # Set max concurrent users to 5
make admin-release         # Free one active slot β†’ admit next user

πŸ”§ Admin API

All endpoints are on http://localhost.

GET /api/admin/status

Returns a live snapshot of the queue.

{
  "capacity": 3,         // max concurrent users
  "active": 2,           // users currently on the protected page
  "queued": 5,           // users waiting in line
  "history_entries": 12  // admission timestamps collected (ETA kicks in at 5)
}

POST /api/admin/capacity

Change how many users can be active at the same time. Queued users are admitted immediately if the new limit allows it.

curl -X POST http://localhost/api/admin/capacity \
  -H "Content-Type: application/json" \
  -d '{"capacity": 5}'

POST /api/admin/release

Evict N active sessions and trigger queue advancement.

curl -X POST http://localhost/api/admin/release \
  -H "Content-Type: application/json" \
  -d '{"count": 1}'

GET /health

Service + Redis health check. Returns {"status":"ok"} or 503.


βš™οΈ How the queue works

Visitor arrives at /
  β”‚
  β”œβ”€β–Ί valid active session? ──YES──► proxied to target βœ…
  β”‚
  └─► no valid session
        β”‚
        β”œβ”€β–Ί capacity free? ──YES──► claim slot (Lua) ──► proxied βœ…
        β”‚
        └─► at capacity
                β”‚
                └─► join FIFO queue ──► redirect to /queue πŸ•
                          β”‚
                          └─► background worker (ticks every 1 s)
                              pops next session when slot opens
                              queue page polls every 2 s
                              on admit β†’ redirect to / βœ…

⏱️ Estimated wait time

Every admission records a Unix timestamp in Redis (capped at 100 entries). Once 5 or more admissions have been recorded, the ETA is calculated as:

ETA = average_interval_between_admissions Γ— (your_position βˆ’ 1)

Until then the queue page shows "Calculating estimated wait…"

πŸ’“ Session TTL & stale-session cleanup

Every session is kept alive by a heartbeat that JavaScript sends every 10 seconds from both the queue page and the protected page. The server stores a heartbeat:{id} key in Redis with a 30-second TTL β€” so a session needs at most three missed pings before it is considered abandoned.

A background reaper runs every 5 seconds and evicts any session whose heartbeat key has expired:

Heartbeat ping every 10 s
        β”‚
        └─► server refreshes heartbeat:{id} TTL to 30 s
                β”‚
                └─► reaper ticks every 5 s
                    checks every active + queued session
                    if heartbeat:{id} is missing β†’ evict
                    then immediately admits next queued user

What happens in each scenario:

Scenario Result
User on protected page closes tab Heartbeat stops β†’ reaper evicts within ~35 s
User on protected page loses connection Heartbeat stops β†’ reaper evicts within ~35 s
User on protected page refreshes Heartbeat resumes on reload β†’ slot preserved
User navigates to a subpage Active session: all paths proxied β†’ slot preserved
User on queue page closes tab Heartbeat stops β†’ reaper evicts within ~35 s
User on queue page refreshes Heartbeat resumes on reload β†’ position preserved

Why no beacon on the queue page? pagehide fires on both tab-close and page-refresh. A beacon here would evict the session on every refresh, bumping the user to the back of the queue. The heartbeat/reaper pair handles cleanup without that side-effect.

πŸ”’ Race condition safety

All slot claims and queue pops are atomic Redis Lua scripts. Two concurrent requests cannot both claim the same last slot β€” the check and the write happen in a single atomic operation on the Redis server.


πŸ—‚οΈ Project structure

queue-based-site-access/
β”œβ”€β”€ compose.yml                       Docker Compose β€” 3 services on an isolated network
β”œβ”€β”€ Makefile                          All operations: up, down, logs, admin
β”‚
β”œβ”€β”€ queue-service/                    Go service (the brain)
β”‚   β”œβ”€β”€ main.go                       Wiring: Redis, proxy, worker, HTTP server
β”‚   β”œβ”€β”€ go.mod / go.sum
β”‚   β”œβ”€β”€ Dockerfile                    Multi-stage build β†’ minimal Alpine image
β”‚   β”‚
β”‚   β”œβ”€β”€ internal/
β”‚   β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”‚   └── config.go             Config struct + env loading
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ queue/
β”‚   β”‚   β”‚   β”œβ”€β”€ store.go              Store struct, public API (admit, join, leave, ETA…)
β”‚   β”‚   β”‚   β”œβ”€β”€ scripts.go            Atomic Redis Lua scripts
β”‚   β”‚   β”‚   └── worker.go             Background worker: admit loop + stale-session reaper
β”‚   β”‚   β”‚
β”‚   β”‚   └── handler/
β”‚   β”‚       β”œβ”€β”€ handler.go            Handler struct, route registration, shared helpers
β”‚   β”‚       β”œβ”€β”€ gate.go               rootHandler, queuePageHandler, positionHandler
β”‚   β”‚       β”œβ”€β”€ session.go            Heartbeat + leave handlers (called by JS on pagehide)
β”‚   β”‚       └── admin.go              Admin handlers: capacity, release, status
β”‚   β”‚
β”‚   └── web/
β”‚       β”œβ”€β”€ queue.html                Waiting room page
β”‚       └── static/
β”‚           β”œβ”€β”€ styles.css            Queue page styles
β”‚           └── app.js                2 s polling, heartbeat ping, auto-redirect on admit
β”‚
└── target/                           Protected destination
    β”œβ”€β”€ Dockerfile                    nginx:alpine β€” no published port
    β”œβ”€β”€ nginx.conf
    └── html/
        β”œβ”€β”€ index.html                "You're In!" home page
        β”œβ”€β”€ about.html                About page (subpage demo)
        β”œβ”€β”€ features.html             Features page (subpage demo)
        └── styles.css                Shared styles incl. top nav

πŸ”‘ Configuration

All values are environment variables on queue-service (see compose.yml).

Variable Default Description
REDIS_ADDR redis:6379 Redis connection address
TARGET_URL http://target:80 Internal URL of the protected service
QUEUE_CAPACITY 3 Initial max concurrent users β€” persists in Redis across restarts
PORT 8080 Port the queue-service listens on
WEB_DIR /web Path to queue.html and static/ assets

πŸ“ Production notes

  • πŸ” Signed cookies β€” Replace the plain UUID qsid cookie with an HMAC-signed value to prevent forgery.
  • πŸ’“ Heartbeat TTL β€” Already implemented: sessions ping every 10 s, reaper evicts stale ones every 5 s. Tune heartbeatTTL in store.go for stricter or more lenient timeouts.
  • πŸ“‘ Real-time updates β€” Replace the 2s polling with Server-Sent Events or WebSockets for instant queue advancement.
  • 🌐 TLS β€” Place a TLS-terminating reverse proxy (e.g. Traefik) in front of queue-service in any public deployment.