Find and fix the first bottleneck

You add a bounded MySQL connection pool and live Prometheus metrics while finding and fixing the first bottleneck under the 300 VU browse workload and recording before-and-after results.

Ticket

The 300 VU browse workload gives you a repeatable way to find the first bottleneck in your service. Use the before measurements from the previous exercise, inspect the running system, and make one targeted change. Do not assume the database is the bottleneck before you check the evidence.

You also add a bounded MySQL connection pool and expose its live statistics through Prometheus. Record the after measurements in after-browse.json and document what changed, what improved, and what you would investigate next.

The tests call these exported declarations:

go
// package database
func Open(ctx context.Context, dsn string) (*sql.DB, error)

// package metrics
func RegisterDBStats(db *sql.DB)

Acceptance criteria

  • Setting DB_MAX_OPEN_CONNS=7 configures the database pool with a maximum of 7 open connections.
  • With DB_MAX_OPEN_CONNS unset or empty, the default maximum is greater than 0 and no greater than 100.
  • With DB_MAX_OPEN_CONNS=4, the maximum open connection limit is 4, and a SELECT 1 query returns 1 without an error.
  • With DB_MAX_OPEN_CONNS=9, registering database statistics exposes db_connections_max_open with value 9.
  • The metrics handler also exposes db_connections_open, db_connections_in_use, and db_connection_waits_total.
  • The after browse run has a p95 no greater than 120% of the before p95, a p99 below 300 ms, and an error rate no greater than 0.01.
  • A README contains a Before and after section with p50, p95, p99, and error measurements for the runs.

Constraints

  • Preserve the existing database.Open(ctx, dsn) signature from W2B3 and its startup ping behavior.
  • Read the maximum open connection limit from DB_MAX_OPEN_CONNS and provide a bounded default.
  • Ensure the maximum idle connection limit never exceeds the maximum open connection limit.
  • Register the four tested database metrics on the existing Prometheus registry. Read their values from db.Stats() at scrape time.
  • Save the after-run summary as backend/loadtest/after-browse.json, beside the before-run summary.
  • Use the same browse.js script and workload for both measurements.
  • Change one thing per run so you can attribute any measured difference.
  • Do not modify the provided tests.

Design direction

Start with the saved before summary from the previous exercise. Run the same 300 VU browse workload and capture a 20-second CPU profile while the test is running. Use pprof to find where CPU time goes, then inspect the hot paths with a CPU profile.

Check the relevant database queries with EXPLAIN. In particular, inspect the orders query and its (user_id, created_at, id) composite index. Look at SHOW FULL PROCESSLIST and the pool statistics to determine whether connections are idle, in use, or waiting.

Do not assume MySQL is the bottleneck. The in-memory rate limiter mutex and menu assembly allocations are also worth investigating. Use the profile and runtime evidence to choose the first change.

For the pool, configure the maximum open connections from the environment and ensure the idle limit stays within it. You can also configure connection lifetime and idle time, using Go duration values. Keep parsing and defaults in small unexported helpers. These are implementation choices, not additional test requirements.

Expose pool statistics with Prometheus callbacks that read db.Stats() each time Prometheus scrapes the existing registry. Include the maximum open connections, open connections, in-use connections, total waits, and total wait duration. Avoid registering duplicate metrics or creating another registry.

After the change, run the same workload and compare the measurements. A better p95 alone does not prove that the pool caused the improvement. Record the conditions of each run and explain what the measurements support.

How to check your work

Start MySQL, Redis, and Redpanda, then run the API and worker. Make sure the pprof listener is available on port 6060.

Run the tests:

bash
cd backend
TEST_MYSQL_DSN="root:dev@tcp(127.0.0.1:3306)/zomato?parseTime=true" make test W=6B5

While the browse workload is running, capture a profile:

bash
cd backend
go tool pprof -http=:0 "http://127.0.0.1:6060/debug/pprof/profile?seconds=20"

Run the after workload and save its summary:

bash
cd backend
k6 run --summary-export=loadtest/after-browse.json loadtest/browse.js

Compare the before and after summaries. Check p50, p95, p99, and error rate, and record the results in the README. If a test fails, start with the first failing assertion and trace it back to the corresponding pool setting, metric, or recorded measurement.

Finished Exercise 6.12?

Load-test baselines

6 items

  • 6.7k6 workload modelsnot completed
  • 6.8CPU and heap profilingnot completed
  • 6.9MySQL query-plan readingnot completed
  • 6.10Capacity from measurementsnot completed
  • 6.11Browse and order k6 scriptsnot completed
  • 6.12Find and fix the first bottlenecknot completed

Backend hardening and admin stats

Up next · Module 4 · 2 items · about 1 h 45 min

Start module 4

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Configure the MySQL connection pool with a bounded open connection limit.
  2. Preserve the existing database startup ping and ensure the idle limit does not exceed the open limit.
  3. Register the four tested database metrics using live db.Stats() values.
  4. Inspect the profile, query plans, process list, and pool statistics before choosing a change.
  5. Run the same 300 VU browse workload and save after-browse.json.
  6. Document the before and after measurements and explain what the results show.

Commands

terminal
cd backend && go tool pprof -http=:0 "http://127.0.0.1:6060/debug/pprof/profile?seconds=20"   # while k6 runs
terminal
cd backend && k6 run --summary-export=loadtest/after-browse.json loadtest/browse.js
terminal
cd backend && TEST_MYSQL_DSN="root:dev@tcp(127.0.0.1:3306)/zomato?parseTime=true" make test W=6B5

Tests

  • TestW6B5_DBPoolStatsAreExported in backend/internal/database/dbstats_test.go
  • TestW6B5_PoolSizeComesFromTheEnvironment in backend/internal/database/pool_test.go
  • TestW6B5_PoolIsBoundedByDefault in backend/internal/database/pool_test.go
  • TestW6B5_IdleConnectionsNeverExceedTheOpenLimit in backend/internal/database/pool_test.go
  • TestW6B5_AfterBrowseIsNotWorseThanBefore in backend/internal/loadtest/loadtest_test.go
  • TestW6B5_AfterBrowseP99IsUnder300ms in backend/internal/loadtest/loadtest_test.go
  • TestW6B5_AfterBrowseHasNoServerErrors in backend/internal/loadtest/loadtest_test.go
  • TestW6B5_ReadmeRecordsTheBeforeAndAfterNumbers in backend/internal/loadtest/loadtest_test.go