Skip to content
CMD
← Back to Blog

Go API Server: Production-Grade REST API

•8 min read•Projects

A high-performance REST API built in Go with JWT authentication, tiered rate limiting, audit logging, and Prometheus observability. Benchmarked with k6 under stress to validate every optimization.

GoGinPostgreSQLJWTPrometheusREST APIArgon2idk6 Benchmarking

A REST API built from scratch in Go, designed around the middleware and infrastructure patterns that production services actually need. It handles authentication, authorization, rate limiting, audit trails, and observability out of the box, with every optimization validated by k6 load testing under stress.

Project Overview

The focus was on three things: security (authentication, authorization, and audit trails that hold up under scrutiny), performance (caching, connection pooling, and rate limiting that don't collapse under load), and observability (metrics and structured logging that tell you what's happening before users do).

Core Requirements

  • JWT authentication with secure cookie-based sessions
  • Tiered rate limiting that reflects real API usage patterns
  • Audit logging that captures every request without slowing them down
  • Structured error responses with centralized domain-to-HTTP error mapping
  • Prometheus metrics for latency, throughput, cache performance, and pool health
  • Benchmarking under stress to validate every optimization with real numbers

Technical Architecture

LayerTechnology
FrameworkGin v1.11, Go 1.24
DatabasePostgreSQL with pgx v5 connection pooling
AuthenticationJWT (HS256) with HTTP-only cookie sessions
Password HashingArgon2id (OWASP-recommended, 46 MiB memory)
Rate LimitingToken bucket with tiered policies
CachingGeneric in-memory cache with TTL + LRU eviction
ObservabilityPrometheus metrics, structured slog logging
Migrationsgolang-migrate with versioned SQL
Load Testingk6 with custom scenario profiles

The project follows a domain-driven layout. Each domain (auth, items, users, audit) owns its handlers, service logic, and repository layer. Shared concerns like middleware, error types, and validation live outside the domain folders so they don't create circular dependencies.

System architecture diagram showing Client to API Gateway (Rate Limiting, JWT Auth, Audit Trail, Metrics) to Application Services (Auth, Users, Items) to Infrastructure (PostgreSQL, TTL Cache, Worker Pool) with sync and async flows

Request Lifecycle

Every request passes through the same middleware chain before reaching a handler. The diagram below shows the full path, from rate limiting and authentication through to the cache layer, service logic, and database, with the audit pipeline running asynchronously so it never adds latency to the response.

Request lifecycle diagram showing the flow through middleware, JWT auth, cache hit/miss branching, service layer, PostgreSQL, and async audit pipeline

Key Design Decisions

Three-Tier Rate Limiting

Rather than a single rate limit applied globally, the API uses three tiers that reflect how endpoints are actually used:

TierRateBurstApplied To
Strict0.2 req/s5Login, registration (unauthenticated)
Standard2.0 req/s10Mutations (create, update, delete)
Relaxed5.0 req/s15Reads (list, get)

Each tier uses a token bucket algorithm with per-user keying when authenticated and per-IP fallback when not. Entries auto-evict after 10 minutes of inactivity, so the limiter doesn't leak memory under sustained traffic. All rate limit rejections are tracked as Prometheus counters, broken down by tier.

Asynchronous Audit Logging

Every request is captured in an audit trail (user, action, resource, method, status, IP, user agent, and request body), but the logging never blocks the response. A worker pool of 10 goroutines pulls events from a buffered channel (1,000 items deep) and batch-inserts them into PostgreSQL. Batches flush every 50 items or every 100ms, whichever comes first.

Sensitive fields like passwords are automatically redacted before capture, and request bodies are truncated at 4KB to prevent oversized payloads from flooding the audit table. The middleware also restores the request body after reading it, so downstream handlers aren't affected.

Argon2id Password Hashing with Concurrency Control

Passwords are hashed with Argon2id using OWASP-recommended parameters (46 MiB memory, 1 iteration, 1 thread). Under load, multiple concurrent hash operations can spike memory usage dangerously, so the API uses a semaphore that limits concurrent hashing to the number of available CPUs. This was one of the biggest performance wins, bringing auth latency under stress down by 86%.

In-Memory User Cache

Authenticated requests need the full user record for authorization checks, which means a database query on every request. The user cache eliminates that bottleneck with a generic Cache[K, V] implementation using Go generics: TTL-based expiration (5 minutes per entry), LRU eviction at 10K entries, and a background cleanup goroutine. Cache hits and misses are tracked as Prometheus metrics.

Prometheus Observability

The API exposes a /metrics endpoint with metrics covering every layer:

  • HTTP: Request counts and duration histograms (11 buckets from 5ms to 10s)
  • Cache: Hit/miss ratios by cache type
  • Rate Limiting: Rejection counts by tier
  • Audit: Queue length and capacity
  • Database: Pool stats (active connections, idle connections, acquire count and duration)

Implementation Details

The API also covers the standard patterns you'd expect from a production service:

  • JWT authentication with HS256-signed tokens in HTTP-only cookies, configurable expiration (default 8 hours), and ownership enforcement at the handler level
  • Transaction management through a context-based transaction manager with automatic rollback on failure, injected as a dependency for testability
  • Structured error responses using sentinel errors (ErrNotFound, ErrUnauthorized, ErrConflict) mapped to consistent JSON via a centralized MapError function. Auth endpoints return generic "invalid credentials" messages to avoid leaking account existence
  • Fetch-limit-plus-one pagination that avoids COUNT(*) queries, capped at 100 items per page

Performance: Optimization Journey

Every optimization was validated with k6 load tests across four profiles: smoke (5 VUs), load (50 VUs), stress (300 VUs), and spike (500 VUs). The benchmarks tracked p50, p95, and p99 latencies along with total throughput, comparing three versions: baseline, infrastructure optimizations (caching + batched audit + connection pool tuning), and the final Argon2id migration with concurrency control.

All benchmarks ran in Docker containers on a Ryzen 9800X3D with 64 GB RAM and no container resource limits. The 9800X3D is relevant here because of two things: strong single-threaded performance and 96 MB of L3 V-Cache. With argonThreads set to 1, each hash runs on a single thread, so single-core speed directly determines per-hash latency. The 96 MB L3 cache also means the 46 MiB Argon2id memory footprint mostly fits in cache, avoiding slower main memory access. On a typical server CPU with 32 MB L3, the same configuration would miss cache more often and hash times would be higher. At peak load (1,000 VUs), the optimized API sustained 4,513 req/s with a p95 of 11ms and 0% failures. The numbers reflect unconstrained, cache-friendly hardware. In a production environment with typical container limits (512 MB to 1 GB RAM, 1 to 2 CPUs) and smaller L3 caches, absolute latencies would be higher, though the relative improvements between optimization rounds should hold.

What Changed

Optimization journey: before (bcrypt 160ms/hash, 25 DB connections, unbounded goroutines, no caching) to after (Argon2id 12ms/hash, 50 DB connections, worker pool of 10, TTL cache and batch writes) with results (p50 694ms to 95ms, 55K to 134K requests, 4513 req/s peak, 0% errors)

Results at a Glance

Performance improvements summary showing 86% auth latency reduction, 75% login latency reduction, 142% auth throughput increase, and 179% login throughput increase

Auth-Flow Latency

The auth flow (register → login → access protected route → logout) saw the most dramatic improvement. Median latency under stress dropped from 694ms to 95ms, an 86% reduction across two optimization rounds.

Auth-flow p50 optimization journey: baseline 694ms to infrastructure 316ms to Argon2id 95ms

The first round (infrastructure) cut latency 54% through user caching, batched audit writes, and connection pool tuning. The second round (Argon2id migration + semaphore limiting) cut it another 70% by eliminating memory contention during concurrent password hashing.

Login Latency

Login-sustained scenarios, where continuous login requests simulate peak authentication load, dropped from 2,607ms to 647ms at the p50 level.

Login p50 optimization journey: baseline 2,607ms to infrastructure 2,623ms to Argon2id 647ms

Infrastructure changes alone didn't help login. The bottleneck was entirely in password hashing. The Argon2id migration with concurrency control solved it in one step.

Throughput Under Stress

Total request throughput during stress tests more than doubled for auth flows and nearly tripled for login flows.

Stress test throughput: auth-flow from 55K to 134K requests, login-sustained from 29K to 81K requests
ScenarioBaselineOptimizedImprovement
Auth-flow55K reqs134K reqs+142%
Login-sustained29K reqs81K reqs+179%

API Endpoints

MethodPathAuthRate LimitDescription
POST/api/v1/auth/registerNoStrictRegister new user
POST/api/v1/auth/loginNoStrictLogin, receive cookie
POST/api/v1/auth/logoutYesStandardClear auth cookie
GET/api/v1/auth/meYesRelaxedCurrent user info
POST/api/v1/itemsYesStandardCreate item
GET/api/v1/itemsYesRelaxedList items (paginated)
GET/api/v1/items/:idYesRelaxedGet item by ID
PUT/api/v1/items/:idYesStandardUpdate item
DELETE/api/v1/items/:idYesStandardDelete item
GET/healthNoNoneHealth check
GET/metricsNoNonePrometheus metrics

What I'd Do Differently

The biggest lesson was optimization order. k6 told me login p50 was 2,607ms under stress, but not why. I spent time tuning connection pools and adding caching, which improved read-heavy flows but did nothing for login. The bottleneck was entirely in password hashing, and no amount of infrastructure tuning would have fixed it. I figured that out by process of elimination (infrastructure changes didn't move the needle, so it had to be hashing), but a pprof CPU profile would have shown argon2id.Hash dominating immediately. k6 tells you what is slow. Profiling tells you why. Next time I'd pair them from the start instead of working backwards from load test results.

What's Next

A few areas I'd explore if taking this further:

  • pprof integration. k6 shows which endpoints are slow, but not where the time goes inside them. Adding Go's built-in pprof would expose CPU hotspots, memory allocation patterns, and lock contention, making it possible to pinpoint bottlenecks directly instead of reasoning backwards from load test results.
  • Distributed rate limiting. The current in-memory token bucket works for a single instance, but horizontal scaling would need a Redis-backed limiter to share state across nodes.
  • Refresh token rotation. Right now sessions are limited to the JWT lifetime. A refresh token flow would allow longer sessions without extending the window for a stolen token.
  • OpenTelemetry tracing. Prometheus covers metrics well, but distributed tracing would make it easier to debug slow requests that span multiple layers.
  • Contract testing. The API has load tests but no consumer-driven contract tests. Adding those would catch breaking changes before they reach clients.