My Go API failed 79% of requests under load. Here's what fixed it.
Load testing LabFlow, a Go lab-management API, with k6 and Grafana: an unbounded connection pool, a 5-query permission check and errors disguised as 403s, and the fixes that took p95 from 8.4 s to 13 ms.
At work I build and run a lab management platform in Next.js and TypeScript. It handles a couple of thousand test records a month for an accredited testing lab. On my own time I rebuilt the same domain in Go as LabFlow, mainly to answer one question: how much load would the Go version actually take?
I’d never measured it. The code had unit tests and CI and “looked fast”, which isn’t a number. So I set up load tests and metrics, and the first real run failed 79.5% of requests.
The setup
LabFlow is a Go API (Gin, GORM, Postgres, Redis) with a React Router frontend. Customers submit test requests, and lab staff move each request through a role-guarded lifecycle, from pending to order_completed. There are 9 roles and 28 permissions, and every protected route checks one.
To measure it I added three things:
- A Prometheus
/metricsendpoint with a request counter, a latency histogram and an in-flight gauge. They’re labelled by route template (/api/reservations/:xid), not the raw path, so Prometheus doesn’t end up with one series per ID. - A Grafana dashboard, provisioned from JSON in the repo, so
docker compose upgives you the same view I had. - A k6 suite with three scenarios running at once, shaped like real lab usage: browse (dashboards, ~85% of traffic), submit (new test requests) and login (bcrypt cost 12, so deliberately CPU-heavy).
I also wrote the targets down before running anything, as k6 thresholds. That makes the test pass or fail instead of just producing numbers:
thresholds: {
'http_req_failed': ['rate<0.01'],
'http_req_duration{scenario:browse}': ['p(95)<100', 'p(99)<250'],
'http_req_duration{scenario:submit}': ['p(95)<250'],
'http_req_duration{scenario:login}': ['p(95)<800'],
},The first run
At 100 browse iterations per second (about 400 requests/s offered), the results were:
scenario p50 p95 p99
browse 747.0ms 8454.2ms 16616.4ms
submit 1216.2ms 9649.7ms 17895.2ms
login 1083.3ms 9334.0ms 17148.5ms
requests: 29323 (280/s) failed: 79.52%The Postgres logs explained most of it. This line appeared 2,794 times:
FATAL: sorry, too many clients alreadyLooking closer, there were actually three separate problems stacked on top of each other.
1. The connection pool had no limit
Go’s database/sql (which GORM uses) allows unlimited open connections by default. Under load, every in-flight request opened its own connection. Postgres allows 100 by default (max_connections), so once traffic passed that, new requests were refused.
You can see it on the dashboard below. During the baseline run, in-flight requests jumped to about 1,000 and goroutines to 2,300, with the 5xx rate climbing to 21%. Requests weren’t slow because Go was slow. They were piling up waiting for a database that had stopped accepting them.

The fix is a few lines:
sqlDB, _ := db.DB()
sqlDB.SetMaxOpenConns(25) // DB_MAX_OPEN_CONNS
sqlDB.SetMaxIdleConns(25)
sqlDB.SetConnMaxLifetime(30 * time.Minute)
sqlDB.SetConnMaxIdleTime(5 * time.Minute)A capped pool means a burst queues briefly in Go instead of failing in Postgres. A short wait for a connection costs milliseconds; a refused connection turns into an error for the user.
2. Every permission check cost five queries
With the pool capped, the next question was why each request needed so much database time. The RBAC middleware looked like this:
func (s *AccessService) HasAccess(ctx context.Context, userID int, perm string) bool {
user, err := s.repo.GetUserByID(ctx, userID) // Preload("Roles.Accesses")
if err != nil {
return false
}
// ...loop over roles and accesses
}Preload("Roles.Accesses") means five queries (the user, the user–role join table, the roles, the role–permission join table, and the permissions) on every protected request, for data that almost never changes. Three of the four API calls in the dashboard view check a permission, so that’s fifteen queries just to repeatedly confirm the same user may read reservations.
I now cache each user’s permission set in memory for 30 seconds (a map guarded by a sync.RWMutex, with an Invalidate(userID) hook). The trade-off is explicit: a role change can take up to 30 seconds to apply. Roles in LabFlow only change through admin operations, so that’s fine. If I ran several API replicas, I’d move the cache to Redis so they share it.
3. The outage looked like a permission problem
This one bothered me most. Look at the if err != nil above: when the database refused a connection, HasAccess returned false, and the middleware answered 403 Permission denied. Of the failed requests in the baseline, 17,156 were 403s. Users who were allowed to see their data were told they weren’t.
That’s worse than a crash. A 403 looks like a client mistake, so it doesn’t show on a 5xx dashboard or trigger an alert, and a support ticket would say “I lost access” instead of “the database is down”.
The fix is to make “I don’t know” a separate answer from “no”:
allowed, err := checker.HasAccess(ctx, userID, permission)
if err != nil {
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "Permission check unavailable"})
return
}
if !allowed {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Permission denied"})
return
}There’s a unit test for each of the three outcomes (allowed, denied, check failed), and another making sure a failed lookup is never cached as an empty permission set.
After
Same machine, same script, same 100 iterations/s:
| Before | After | |
|---|---|---|
| Browse p95 | 8,454 ms | 13.5 ms |
| Browse p99 | 16,616 ms | 38 ms |
| Submit p95 | 9,650 ms | 66 ms |
| Failed requests | 79.5% | 0.00% |
| “too many clients” errors | 2,794 | 0 |
Then I doubled the load to 200 iterations/s: 680 requests/s, 88,824 requests, zero failures. But browse p95 rose to 671 ms, well past my 100 ms target. Every route slowed down together, including trivial ones like /api/auth/me. That pattern points to shared capacity rather than one slow query: requests waiting for one of the 25 connections while bcrypt logins use the CPU. All of this ran on one laptop (an i3 with 8 GB of RAM) that was also running k6, Postgres and Prometheus, so it’s a floor, not a ceiling. The next step is profiling with pprof to separate pool-wait time from bcrypt time, rather than guessing.
Making it stay fixed
A one-off load test only shows how the app performed that day. To catch regressions, the CI pipeline now starts the whole stack in Docker, seeds it, and runs two things on every pull request:
- Playwright e2e tests: login, RBAC, logout actually revoking the token (by replaying the old token after logout), and a reservation that a customer submits and QA rejects.
- A short k6 smoke run with the same thresholds. If a change makes p95 regress, the build fails, the same as a broken unit test.
What I took away
- Defaults aren’t production settings. An unlimited pool is fine on a laptop and fails under real traffic. Set pool limits deliberately.
- Look at what runs on every request. Middleware runs on every call, so five queries there cost more than a slow report endpoint someone opens once a day.
- Don’t turn errors into denials. “I couldn’t check” and “no” need different status codes, or your monitoring will report an outage as user error.
- Set the targets before you measure. Writing the thresholds first is what made the 79% failure rate an obvious fail rather than something to explain away.
The code, dashboard and recorded k6 results are all in the LabFlow repository, and its performance section links each fix to the code that changed.