Golang Performance Baseline: k6 Load Test, pprof Profiling, Benchmarks
Establish the Santekno Shop performance baseline with k6 load testing, Go pprof CPU/memory profiling, benchmark testing, and database query optimization driven by trace results.
Before we can claim “our system is faster,” we need a measurable performance baseline. Without an initial number, every optimization claim is just a feeling — not a fact. In this article we establish the Santekno Shop baseline with k6 load testing, pprof profiling, and Go benchmarks, then identify the first bottleneck worth tackling.
The focus isn’t chasing fantastic numbers, but building a reproducible way to measure: the same number appears again when you rerun, so before/after comparisons become valid.
19.01 Why Performance Baseline First?
Optimizing without a baseline is shooting in the dark. The illustration below compares the situation without and with a baseline, and names the five key metrics we’re after.
1WITHOUT BASELINE:
2 "We optimized this query" -> how much improvement?
3 "Response is faster" -> from what to what?
4 "Load balancer added" -> what's the impact?
5 CANNOT BE ANSWERED.
6
7WITH BASELINE:
8 Before: P95 latency 850ms, 45 RPS sustained
9 After: P95 latency 180ms, 280 RPS sustained
10 Improvement: latency -79%, throughput +522%
11
12The baseline we're after:
13 1. Maximum sustainable RPS (requests per second)
14 2. Latency percentiles at various loads (p50/p95/p99)
15 3. Resource utilization: CPU, memory, DB connections
16 4. Error rate as we approach saturation
17 5. The first bottleneck that appearsThe point: a baseline turns qualitative statements (“faster”) into a quantitative delta you can defend in review and to stakeholders.
19.02 k6 Load Test: Authentication Flow
The first load test targets the authentication flow because bcrypt deliberately makes this endpoint “heavy.” The k6 script below ramps the load from 10 to 100 virtual users, measures login duration as a custom metric, and enforces latency thresholds tied to the SLO.
1// tests/load/auth_flow.js
2
3import http from 'k6/http';
4import { check, sleep } from 'k6';
5import { Trend, Rate, Counter } from 'k6/metrics';
6
7// Custom metrics
8const loginDuration = new Trend('login_duration');
9const loginErrors = new Rate('login_errors');
10const successfulLogins = new Counter('successful_logins');
11
12export const options = {
13 stages: [
14 { duration: '1m', target: 10 }, // Ramp up
15 { duration: '3m', target: 10 }, // Steady state low
16 { duration: '1m', target: 50 }, // Ramp up higher
17 { duration: '3m', target: 50 }, // Steady state medium
18 { duration: '1m', target: 100 }, // Peak
19 { duration: '2m', target: 100 }, // Sustain peak
20 { duration: '1m', target: 0 }, // Ramp down
21 ],
22 thresholds: {
23 http_req_duration: ['p(95)<500', 'p(99)<1000'], // Latency SLO
24 http_req_failed: ['rate<0.01'], // Error rate < 1%
25 login_errors: ['rate<0.01'],
26 'http_req_duration{name:register}': ['p(95)<300'],
27 'http_req_duration{name:login}': ['p(95)<200'],
28 },
29};
30
31const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
32
33export function setup() {
34 // No setup needed because each VU registers itself
35}
36
37export default function () {
38 // Unique email per VU per iteration
39 const email = `loadtest-${__VU}-${__ITER}@test.com`;
40 const password = 'LoadTest123';
41
42 // Register
43 const regRes = http.post(`${BASE_URL}/api/v1/auth/register`,
44 JSON.stringify({ email, password, name: `User ${__VU}` }),
45 { headers: { 'Content-Type': 'application/json' }, tags: { name: 'register' } }
46 );
47 check(regRes, { 'register 201': (r) => r.status === 201 });
48
49 // Login
50 const loginStart = Date.now();
51 const loginRes = http.post(`${BASE_URL}/api/v1/auth/login`,
52 JSON.stringify({ email, password }),
53 { headers: { 'Content-Type': 'application/json' }, tags: { name: 'login' } }
54 );
55
56 loginDuration.add(Date.now() - loginStart);
57 const loginOK = check(loginRes, { 'login 200': (r) => r.status === 200 });
58 loginErrors.add(!loginOK);
59 if (loginOK) successfulLogins.add(1);
60
61 sleep(1); // Simulate think time
62}
63
64// Run:
65// k6 run tests/load/auth_flow.js --env BASE_URL=http://localhost:8080
What matters: k6 marks the test as failed (non-zero exit code) the moment any threshold is breached, so this script doubles as a CI gate, not just a measuring tool.
19.03 k6 Load Test: Place Order Flow
The order flow is more complex because it involves browse, place order, and get orders within a single VU session. The script below uses group so each stage is measured separately, and injects a unique idempotency key to make client behavior realistic.
1// tests/load/place_order_flow.js
2
3import http from 'k6/http';
4import { check, sleep, group } from 'k6';
5
6export const options = {
7 stages: [
8 { duration: '2m', target: 20 }, // Warm up
9 { duration: '5m', target: 20 }, // Baseline
10 { duration: '2m', target: 50 }, // Medium load
11 { duration: '3m', target: 50 }, // Sustain
12 { duration: '2m', target: 100 }, // High load
13 { duration: '3m', target: 100 }, // Sustain high
14 { duration: '1m', target: 0 }, // Ramp down
15 ],
16 thresholds: {
17 'http_req_duration{name:place_order}': ['p(95)<1000', 'p(99)<2000'],
18 'http_req_duration{name:get_orders}': ['p(95)<200'],
19 http_req_failed: ['rate<0.01'],
20 },
21};
22
23const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
24
25// Seed product ID (must exist in DB before the load test)
26const PRODUCT_ID = __ENV.PRODUCT_ID || '550e8400-e29b-41d4-a716-446655440000';
27
28export function setup() {
29 // Login as a pre-seeded user for all VUs
30 // (more realistic: each VU has its own user)
31 const res = http.post(`${BASE_URL}/api/v1/auth/login`,
32 JSON.stringify({ email: 'loadtest@santekno.com', password: 'LoadTest123' }),
33 { headers: { 'Content-Type': 'application/json' } }
34 );
35 return { token: res.json('access_token') };
36}
37
38export default function (data) {
39 const headers = {
40 'Content-Type': 'application/json',
41 'Authorization': `Bearer ${data.token}`,
42 // Unique idempotency key per request
43 'Idempotency-Key': `${__VU}-${__ITER}-${Date.now()}`,
44 };
45
46 group('browse products', () => {
47 const res = http.get(`${BASE_URL}/api/v1/products?limit=10`, { tags: { name: 'list_products' } });
48 check(res, { 'products 200': (r) => r.status === 200 });
49 });
50
51 sleep(0.5);
52
53 group('place order', () => {
54 const res = http.post(`${BASE_URL}/api/v1/orders`,
55 JSON.stringify({
56 items: [{ product_id: PRODUCT_ID, quantity: 1 }],
57 shipping_address_id: '00000000-0000-0000-0000-000000000001',
58 payment_method: 'QRIS',
59 }),
60 { headers, tags: { name: 'place_order' } }
61 );
62 check(res, { 'order 201': (r) => r.status === 201 });
63 });
64
65 sleep(1);
66
67 group('get orders', () => {
68 const res = http.get(`${BASE_URL}/api/v1/orders`, { headers, tags: { name: 'get_orders' } });
69 check(res, { 'orders 200': (r) => r.status === 200 });
70 });
71
72 sleep(2);
73}By separating the threshold per name, we can immediately tell which stage exceeds the SLO — place order may go up to 1s P95, but get orders must stay under 200ms.
19.04 k6 Spike Test
Besides gradual load, we need to test sudden surges to see whether the system recovers after a spike. The concise config below jumps the load from 10 to 500 VUs in 10 seconds, then returns it to normal.
1// tests/load/spike_test.js
2// Test: does the system recover from a traffic spike?
3
4export const options = {
5 stages: [
6 { duration: '30s', target: 10 }, // Normal
7 { duration: '10s', target: 500 }, // SPIKE!
8 { duration: '1m', target: 500 }, // Sustain spike
9 { duration: '10s', target: 10 }, // Back to normal
10 { duration: '2m', target: 10 }, // Recovery
11 ],
12 thresholds: {
13 http_req_failed: ['rate<0.05'], // 5% errors allowed during spike
14 'http_req_duration{name:list_products}': ['p(95)<2000'],
15 },
16};The threshold here is deliberately looser (5% errors tolerated): the goal isn’t zero errors during a spike, but making sure the system doesn’t get stuck and returns to health after the load drops.
19.05 Benchmark Tests
Load tests measure the system end-to-end; benchmarks measure a single use case at the micro level. The PlaceOrder benchmark below uses a mock repository and b.RunParallel to simulate concurrent requests without touching the database.
1// internal/usecase/order/place_order_bench_test.go
2//go:build bench
3
4package order_test
5
6import (
7 "context"
8 "testing"
9
10 "go.uber.org/mock/gomock"
11 "github.com/google/uuid"
12)
13
14func BenchmarkPlaceOrder_SingleItem(b *testing.B) {
15 ctrl := gomock.NewController(b)
16 defer ctrl.Finish()
17
18 productRepo := mock.NewMockProductRepository(ctrl)
19 orderRepo := mock.NewMockOrderRepository(ctrl)
20 publisher := mock.NewMockPublisher(ctrl)
21
22 product := &domainProduct.Product{
23 ID: uuid.New(), PriceIDR: 100_000_00, Stock: 10000, IsActive: true,
24 }
25
26 productRepo.EXPECT().GetByID(gomock.Any(), gomock.Any()).Return(product, nil).AnyTimes()
27 orderRepo.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
28 publisher.EXPECT().Publish(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
29
30 uc := order.NewPlaceOrderUseCase(orderRepo, productRepo, publisher)
31 userID := uuid.New()
32 productID := product.ID
33
34 b.ResetTimer()
35 b.RunParallel(func(pb *testing.PB) {
36 for pb.Next() {
37 uc.Execute(context.Background(), orderUC.PlaceOrderInput{
38 UserID: userID,
39 Items: []orderUC.PlaceOrderItem{{ProductID: productID, Quantity: 1}},
40 PaymentMethod: domainOrder.PaymentQRIS,
41 })
42 }
43 })
44}
45
46// Run:
47// go test -bench=BenchmarkPlaceOrder -benchmem -tags=bench ./internal/usecase/order/
48// Output: ns/op, B/op, allocs/opThe -benchmem flag surfaces B/op and allocs/op — the two numbers most often targeted for optimization, because excess allocation burdens the garbage collector.
19.06 Password Hashing Benchmark
bcrypt is a deliberate bottleneck, and this benchmark verifies its cost explicitly. We compare cost 12 and cost 10 to understand the security-versus-registration-throughput trade-off.
1// internal/usecase/auth/register_bench_test.go
2//go:build bench
3
4func BenchmarkRegisterUser_bcryptCost12(b *testing.B) {
5 // bcrypt is a deliberate bottleneck - benchmark to verify
6 b.ReportAllocs()
7 for i := 0; i < b.N; i++ {
8 bcrypt.GenerateFromPassword([]byte("BenchmarkPassword123"), 12)
9 }
10}
11
12func BenchmarkRegisterUser_bcryptCost10(b *testing.B) {
13 for i := 0; i < b.N; i++ {
14 bcrypt.GenerateFromPassword([]byte("BenchmarkPassword123"), 10)
15 }
16}
17
18// Expected output:
19// BenchmarkRegisterUser_bcryptCost12-8 4 289ms/op <- ~4 registrations/second
20// BenchmarkRegisterUser_bcryptCost10-8 16 74ms/op <- ~16/second
21
22// Cost 12 is the security vs performance sweet spot.
23// A registration rate of 4/s is acceptable for a low-frequency endpoint.The conclusion: cost 12 only manages ~4 registrations/second, and that’s genuinely acceptable — registration is a low-frequency endpoint, while brute-force protection is far more important.
19.07 Database Query Benchmark
Repository benchmarks measure real queries against PostgreSQL, not mocks. The two benchmarks below compare listing products without search versus with full-text search so the impact of the GIN index becomes visible.
1// internal/repository/postgres/product_repository_bench_test.go
2//go:build bench,integration
3
4func BenchmarkProductRepository_List_NoSearch(b *testing.B) {
5 pool := testdb.Setup(b)
6 repo := postgres.NewProductRepository(pool)
7 ctx := context.Background()
8
9 b.ResetTimer()
10 for i := 0; i < b.N; i++ {
11 repo.List(ctx, domainProduct.SearchFilter{Page: 1, Limit: 10})
12 }
13}
14
15func BenchmarkProductRepository_List_WithFullTextSearch(b *testing.B) {
16 pool := testdb.Setup(b)
17 repo := postgres.NewProductRepository(pool)
18 ctx := context.Background()
19
20 b.ResetTimer()
21 for i := 0; i < b.N; i++ {
22 repo.List(ctx, domainProduct.SearchFilter{
23 Query: "running shoes", Page: 1, Limit: 10,
24 })
25 }
26}
27
28// Expected:
29// BenchmarkProductRepository_List_NoSearch-8 500 2.1ms/op (index scan)
30// BenchmarkProductRepository_List_WithFullTextSearch 200 5.3ms/op (GIN index)The 2.1ms versus 5.3ms difference confirms full-text search is indeed more expensive, but still under control because the GIN index is active — without an index, the number could be tens of times higher.
19.08 pprof CPU Profile Analysis
Once we know the aggregate numbers, pprof shows which function consumes the CPU. The steps below run a light load test, capture a 30-second CPU profile, then analyze it interactively.
1# Profiling steps:
2
3# 1. Run a light load test in the background
4k6 run --vus=10 --duration=60s tests/load/place_order_flow.js &
5
6# 2. Capture the CPU profile (30 seconds)
7curl -s http://localhost:6060/debug/pprof/profile?seconds=30 > cpu.prof
8
9# 3. Interactive analysis
10go tool pprof -http=:8081 cpu.prof
11# Open http://localhost:8081
12
13# Alternative: text output
14go tool pprof cpu.prof
15> top15 # 15 functions with the highest CPU
16> web # open the flame graph in a browser
17> list placeOrder # view annotated source code
18
19# Typical findings in Santekno Shop:
20# 1. bcrypt.GenerateFromPassword: 65% CPU during a load test with registration
21# -> Expected! bcrypt cost 12 is by design
22# 2. json.Marshal: 12% CPU
23# -> Can be optimized with an encoding/json stream or fastjson
24# 3. pgxpool.Query: 15% CPU
25# -> Needs query plan analysisThe typical findings confirm the benchmark hypothesis: bcrypt dominates when registration is involved, while json.Marshal and the database query are the next optimization candidates.
19.09 Memory Profile Analysis
Beyond CPU, we need to make sure there’s no memory leak or goroutine leak. The commands below capture a heap profile, a goroutine dump, and a scheduler trace for inspection.
1# Heap profile
2curl -s http://localhost:6060/debug/pprof/heap > heap.prof
3go tool pprof -http=:8082 heap.prof
4
5# Goroutine dump (to detect goroutine leaks)
6curl http://localhost:6060/debug/pprof/goroutine?debug=1 | head -50
7
8# Typical patterns:
9# - "waiting for connection": DB pool exhaustion
10# - "select": goroutines waiting on channels (normal)
11# - High goroutine count growing over time: GOROUTINE LEAK
12
13# Trace (view the scheduler)
14curl -s http://localhost:6060/debug/pprof/trace?seconds=5 > trace.out
15go tool trace trace.outThe most important signal here is a goroutine count that keeps rising over time — that’s a sign of a leak that must be investigated before going to production.
19.10 Baseline Results: Expected Metrics
All the measurements above culminate in the baseline table. The summary below records the test environment, per-endpoint latency, and the order of identified bottlenecks.
1Test Environment:
2 App: 1 replica, 1 CPU, 512MB memory
3 DB: PostgreSQL 15, 25 max connections
4 Redis: 1 instance
5 k6: 50 concurrent users, 5 minutes
6
7Expected Baseline (before optimization):
8
9Endpoint | P50 | P95 | P99 | RPS
10--------------------|-------|--------|--------|-----
11GET /products | 12ms | 45ms | 120ms | 180
12POST /auth/register | 280ms | 310ms | 350ms | 15
13POST /auth/login | 85ms | 120ms | 180ms | 45
14POST /orders | 95ms | 180ms | 350ms | 40
15DELETE /orders/:id | 45ms | 90ms | 150ms | 30
16GET /orders | 20ms | 55ms | 100ms | 80
17
18System Resources at 50 VU:
19 CPU: 25-35%
20 Memory: 180MB RSS
21 DB connections: 12-18 / 25
22 Cache hit rate: 65%
23 Error rate: 0.02%
24
25Bottleneck order:
26 1. bcrypt (register) - by design, limit registration rate
27 2. DB transaction (place order) - atomic tx overhead
28 3. Full-text search (product list with query) - GIN index neededThis table is our “zero point”: every optimization in later articles will be compared against it to prove a real impact.
19.11 EXPLAIN ANALYZE for PlaceOrder
To make sure the key queries use an index, we run EXPLAIN ANALYZE. The three queries on the PlaceOrder path below are checked one by one.
1-- Analyze the most frequent queries in PlaceOrder
2
3-- 1. Check product availability
4EXPLAIN ANALYZE
5UPDATE products
6SET reserved_stock = reserved_stock + 1, updated_at = NOW()
7WHERE id = '550e8400-e29b-41d4-a716-446655440000'
8 AND (stock - reserved_stock) >= 1
9 AND is_active = true;
10
11-- Expected output:
12-- Update on products (cost=0.29..8.31 rows=1 width=6)
13-- -> Index Scan using products_pkey on products (cost=0.29..8.31)
14-- Index Cond: (id = '...')
15-- Filter: ((stock - reserved_stock) >= 1 AND is_active = true)
16--
17-- Execution Time: 0.5ms <- Good!
18
19-- 2. Insert order items (batch)
20EXPLAIN ANALYZE
21INSERT INTO order_items (order_id, product_id, product_name, unit_price_idr, quantity, subtotal_idr)
22VALUES ($1, $2, $3, $4, $5, $6);
23-- Expected: ~0.3ms per item
24
25-- 3. Outbox insert
26EXPLAIN ANALYZE
27INSERT INTO outbox_events (event_type, topic, payload)
28VALUES ('order.placed', 'santekno.orders.placed', '{}');
29-- Expected: ~0.2msThe keyword to look for is Index Scan, not Seq Scan. As long as every query uses an index and execution time stays under 1ms, the PlaceOrder path is safe from the database side.
19.12 Identify and Fix the N+1 Bottleneck
A classic bottleneck on list endpoints is the N+1 query. The example below shows the wrong version that fires one query per order, then the correct version that pulls them in a single batch.
1// BUG: N+1 query problem in GetOrders (not in our code, but a preview)
2
3// WRONG - N+1:
4func (r *OrderRepository) ListByUserID(...) ([]*Order, int, error) {
5 rows, _ := r.db.Query(ctx, "SELECT id FROM orders WHERE user_id = $1", userID)
6 for rows.Next() {
7 var id uuid.UUID
8 rows.Scan(&id)
9 items, _ := r.getOrderItems(ctx, id) // <- N+1! one query per order
10 orders = append(orders, &Order{Items: items})
11 }
12}
13
14// RIGHT - single query with JOIN or batch
15func (r *OrderRepository) ListByUserID(...) ([]*Order, int, error) {
16 // Fetch orders first
17 orders, _ := r.queryOrders(ctx, userID, page, limit)
18
19 // Fetch all items in a single query
20 orderIDs := extractIDs(orders)
21 items, _ := r.queryItemsByOrderIDs(ctx, orderIDs) // one query
22
23 // Map items to orders
24 itemsByOrderID := groupByOrderID(items)
25 for _, o := range orders {
26 o.Items = itemsByOrderID[o.ID]
27 }
28 return orders, total, nil
29}The correct pattern turns N+1 queries into a fixed 2 queries, no matter how many orders there are — a decisive difference when a user has hundreds of orders.
19.13 Redis Cache Impact Measurement
To prove the cache truly has an impact, we measure with and without Redis. The two k6 runs below compare cold cache versus warm cache on the product list endpoint.
1# Measure cache impact by comparing:
2# Test A: Redis disabled (or forced cache miss)
3# Test B: Redis enabled (warm cache)
4
5# Test A: cold cache
6curl -X DELETE http://localhost:8080/api/v1/admin/cache/flush # flush cache
7k6 run --vus=20 --duration=2m \
8 --env CACHE_ENABLED=false tests/load/place_order_flow.js
9
10# Test B: warm cache
11k6 run --vus=20 --duration=2m \
12 --env CACHE_ENABLED=true tests/load/place_order_flow.js
13
14# Expected comparison:
15# GET /products (cold): P95 45ms, cache miss: 100%
16# GET /products (warm): P95 8ms, cache hit: 85%
17# Improvement: 5x latency reduction for list productsThe 45ms dropping to 8ms (5x faster) gives a quantitative justification for keeping the cache around — not just an assumption that “cache surely helps.”
19.14 Load Test Data Preparation
The baseline is only valid if the data is realistic. The seed script below fills 1000 products, one load-test user, and a mock shipping address before k6 runs.
1-- Seed script for the load test
2-- Run before k6
3
4-- Seed 1000 products
5INSERT INTO products (name, description, price_idr, stock, is_active)
6SELECT
7 'Product ' || i AS name,
8 'Description for product ' || i AS description,
9 (100 + (i % 10) * 50) * 100 AS price_idr, -- Rp 10,000 - Rp 55,000
10 1000 AS stock,
11 true AS is_active
12FROM generate_series(1, 1000) AS i;
13
14-- Seed load test user
15INSERT INTO users (email, password_hash, name, is_active)
16VALUES (
17 'loadtest@santekno.com',
18 '$2a$12$xyz...', -- bcrypt hash of 'LoadTest123'
19 'Load Test User',
20 true
21);
22
23-- Seed shipping address (mock)
24INSERT INTO shipping_addresses (id, user_id, street, city)
25VALUES ('00000000-0000-0000-0000-000000000001',
26 (SELECT id FROM users WHERE email = 'loadtest@santekno.com'),
27 'Jl. Load Test No. 1', 'Jakarta');With 1000 products, the query plan, GIN index, and cache hit rate reflect production conditions — so the baseline isn’t biased by a dataset that’s too small.
19.15 Performance Baseline Report
The measurement results need to be documented in a format that can be compared over time. The report template below records the configuration, results summary, bottlenecks, and pass/fail status against the SLO.
1# Santekno Shop Performance Baseline Report
2Date: 2027-02-25
3Version: v1.0.0
4Environment: Staging (1 CPU, 512MB)
5
6## Test Configuration
7- Tool: k6
8- Duration: 12 minutes per test
9- Load profile: ramp 10->50->100 VUs
10- Data: 1000 products, 1 test user
11
12## Results Summary
13
14| Endpoint | P50 | P95 | P99 | Throughput | Error Rate |
15|----------|-----|-----|-----|------------|------------|
16| GET /products | 12ms | 45ms | 120ms | 180 RPS | 0.0% |
17| POST /auth/register | 280ms | 310ms | 350ms | 15 RPS | 0.0% |
18| POST /auth/login | 85ms | 120ms | 180ms | 45 RPS | 0.0% |
19| POST /orders | 95ms | 180ms | 350ms | 40 RPS | 0.01% |
20| DELETE /orders/:id | 45ms | 90ms | 150ms | 30 RPS | 0.0% |
21
22## Resource Utilization at 50 VU
23- CPU: 28% average
24- Memory: 185MB RSS
25- DB connections: 14/25 average
26- Cache hit rate: 68%
27
28## Bottlenecks Identified
291. bcrypt cost 12 limits registration to ~15 RPS (acceptable)
302. DB transaction in PlaceOrder: 95ms P50 (acceptable, improve at scale)
313. Full-text search without cache: 45ms P95 (optimize with Article 13 cache)
32
33## Pass/Fail vs SLO
34- Availability: PASS (error rate < 0.01%)
35- P95 Latency < 500ms: PASS (all endpoints)
36- Order P99 < 2s: PASS (350ms < 2000ms)
37
38## Next Actions
39-> Add product list cache (Article 13 already implemented)
40-> Benchmark with 3 app replicas
41-> Load test Article 20 (AI features) to measure LLM overheadA structured report like this becomes an artifact you can commit to the repo, so anyone can compare old and new baselines without guessing the context.
19.16 Continuous Performance Testing
A baseline that isn’t maintained goes stale. The GitHub Actions workflow below runs a weekly load test and fails the build if P95 exceeds the threshold.
1# .github/workflows/perf-test.yml
2
3name: Performance Baseline Check
4
5on:
6 schedule:
7 - cron: '0 4 * * 1' # Weekly, Monday 4 AM
8 workflow_dispatch:
9
10jobs:
11 load-test:
12 name: "k6 Load Test"
13 runs-on: ubuntu-latest
14 steps:
15 - uses: actions/checkout@v4
16
17 - name: Start test environment
18 run: docker-compose -f docker-compose.test.yml up -d
19
20 - name: Wait for services
21 run: sleep 30
22
23 - name: Seed test data
24 run: psql "$TEST_DB_URL" < testdata/seed_load_test.sql
25
26 - name: Run k6 load test
27 uses: grafana/k6-action@v0.3.1
28 with:
29 filename: tests/load/place_order_flow.js
30 flags: --env BASE_URL=http://localhost:8080 --out json=results.json
31
32 - name: Parse results and check thresholds
33 run: |
34 P95=$(cat results.json | jq '.metrics.http_req_duration.values.p95')
35 echo "P95: $P95 ms"
36 if (( $(echo "$P95 > 500" | bc -l) )); then
37 echo "P95 latency $P95ms exceeds 500ms threshold"
38 exit 1
39 fi
40
41 - name: Upload results
42 uses: actions/upload-artifact@v4
43 with:
44 name: k6-results-${{ github.run_number }}
45 path: results.jsonWith this scheduled job, performance regressions are detected automatically every week, not when users complain in production.
19.17 Go Benchmark Comparison: Before/After
To compare optimization results statistically, we use benchstat. The command sequence below saves the baseline, runs the benchmark after optimization, then computes the delta along with its p-value.
1# Save the baseline benchmark
2go test -bench=. -benchmem -tags=bench ./internal/... > benchmark-baseline.txt
3
4# After optimization (example: cache + query tuning):
5go test -bench=. -benchmem -tags=bench ./internal/... > benchmark-after.txt
6
7# Compare with benchstat:
8go install golang.org/x/perf/cmd/benchstat@latest
9benchstat benchmark-baseline.txt benchmark-after.txt
10
11# Sample output:
12# goos: linux
13# goarch: amd64
14# pkg: github.com/santekno/santekno-shop/internal/usecase/order
15# BenchmarkPlaceOrder-8
16# baseline after delta
17# time/op 450us +-2% 380us +-3% -15.6% (p=0.008)
18# alloc/op 28kB +-1% 22kB +-2% -21.4% (p=0.002)
19# allocs/op 145 +-0% 118 +-0% -18.6% (p=0.008)A p value below 0.05 confirms the improvement is statistically significant, not just measurement noise — this is what separates a serious optimization claim from a hopeful one.
19.18 Goroutine Leak Detection
Goroutine leaks often slip through because they don’t immediately crash the system. The VerifyNoLeak helper below compares the goroutine count before and after running the target function.
1// testutil/goroutine/leak.go
2
3package goroutine
4
5import (
6 "runtime"
7 "testing"
8 "time"
9)
10
11// VerifyNoLeak: assert there is no goroutine leak after the test
12func VerifyNoLeak(t *testing.T, fn func()) {
13 t.Helper()
14 before := runtime.NumGoroutine()
15 fn()
16
17 // Give goroutines time to clean up
18 deadline := time.Now().Add(5 * time.Second)
19 for time.Now().Before(deadline) {
20 after := runtime.NumGoroutine()
21 if after <= before+1 { return }
22 time.Sleep(100 * time.Millisecond)
23 }
24
25 after := runtime.NumGoroutine()
26 if after > before+1 {
27 t.Errorf("goroutine leak: before=%d, after=%d", before, after)
28 }
29}
30
31// Usage:
32func TestSomeHandler_DoesNotLeakGoroutines(t *testing.T) {
33 goroutine.VerifyNoLeak(t, func() {
34 // Call a handler that spawns a goroutine
35 h.PlaceOrder(ctx, req)
36 })
37}This helper allows a cleanup grace period before judging, so it won’t wrongly accuse a goroutine that is legitimately in the process of stopping of being a leak.
19.19 Production Profiling Checklist
Before every production deploy, there’s a profiling checklist that must pass. The list below summarizes the CPU, memory, goroutine, and database thresholds that must be verified.
1Before each production deploy, verify:
2
3CPU Profile:
4 [ ] No unexpected hotspot (> 20% CPU single function besides bcrypt)
5 [ ] GC pause < 10ms P99
6 [ ] json.Marshal doesn't dominate (a sign of many allocations)
7
8Memory Profile:
9 [ ] Heap growth rate < 5MB per minute under steady load
10 [ ] No memory leak (heap grows unbounded)
11 [ ] Buffer pool reuse rate > 80%
12
13Goroutines:
14 [ ] Goroutine count stable (not continuously rising)
15 [ ] No goroutine blocked > 30 seconds
16
17DB:
18 [ ] Connection pool usage < 80% at peak load
19 [ ] All queries use an index (no full table scan)
20 [ ] Transaction duration P95 < 100msThis checklist turns profiling from an ad-hoc activity into a consistent release gate, so regressions get caught before they reach users.
19.20 Summary: Performance Baseline Established
Santekno Shop now has a measurable and reproducible performance baseline. The recap below closes out everything we built in this article.
- k6 Load Tests: auth flow, order flow, spike test — all with thresholds linked to the SLO.
- Benchmarks: usecase benchmarks (mock), repository benchmarks (real DB), password hashing benchmarks.
- pprof: a reproducible CPU and memory profiling workflow.
- Baseline metrics: P95 latency, throughput, resource utilization per endpoint — all documented.
- Bottlenecks identified: bcrypt (by design), DB transaction PlaceOrder (acceptable), full-text search (mitigated by cache).
With a solid baseline, every subsequent change — including adding AI features in Topic 6 — can have its performance impact measured precisely, not guessed.