Golang Performance Baseline: k6 Load Test, pprof Profiling, Benchmarks
Establish performance baseline Santekno Shop dengan k6 load testing, Go pprof CPU/memory profiling, benchmark testing, dan database query optimization dari hasil trace.
Sebelum kita bisa mengklaim “sistem kita lebih cepat”, kita butuh performance baseline yang terukur. Tanpa angka awal, setiap klaim optimasi hanya perasaan — bukan fakta. Di artikel ini kita establish baseline Santekno Shop dengan k6 load testing, pprof profiling, dan Go benchmarks, lalu mengidentifikasi bottleneck pertama yang layak kita tangani.
Fokusnya bukan mengejar angka fantastis, tapi membangun cara ukur yang reproducible: nomor yang sama muncul lagi saat kamu jalankan ulang, sehingga perbandingan before/after menjadi valid.
19.01 Kenapa Performance Baseline Dulu?
Optimasi tanpa baseline adalah menembak dalam gelap. Ilustrasi berikut membandingkan situasi tanpa dan dengan baseline, serta menyebut lima metrik utama yang kita kejar.
1TANPA BASELINE:
2 "Kita optimize query ini" -> berapa improvement-nya?
3 "Response lebih cepat" -> dari berapa ke berapa?
4 "Load balancer ditambah" -> apa dampaknya?
5 TIDAK BISA DIJAWAB.
6
7DENGAN BASELINE:
8 Before: P95 latency 850ms, 45 RPS sustained
9 After: P95 latency 180ms, 280 RPS sustained
10 Improvement: latency -79%, throughput +522%
11
12Baseline yang kita cari:
13 1. Maximum sustainable RPS (requests per second)
14 2. Latency percentiles di berbagai load (p50/p95/p99)
15 3. Resource utilization: CPU, memory, DB connections
16 4. Error rate saat mendekati saturation
17 5. Bottleneck pertama yang munculIntinya: baseline mengubah pernyataan kualitatif (“lebih cepat”) menjadi delta kuantitatif yang bisa dipertanggungjawabkan di review maupun ke stakeholder.
19.02 k6 Load Test: Authentication Flow
Load test pertama menyasar authentication flow karena bcrypt membuat endpoint ini sengaja “berat”. Script k6 berikut me-ramp beban dari 10 hingga 100 virtual user, mengukur durasi login sebagai custom metric, dan menegakkan threshold latency yang terikat 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 // Setup tidak perlu karena setiap VU register sendiri
35}
36
37export default function () {
38 // Unik 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
Yang perlu diperhatikan: k6 akan menandai test gagal (exit code non-zero) begitu salah satu threshold terlanggar, jadi script ini sekaligus menjadi gate CI, bukan sekadar pengukur.
19.03 k6 Load Test: Place Order Flow
Order flow lebih kompleks karena melibatkan browse, place order, dan get orders dalam satu sesi VU. Script berikut memakai group agar tiap tahap terukur terpisah, dan menyuntik idempotency key unik supaya perilaku client realistis.
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 (harus ada di DB sebelum load test)
26const PRODUCT_ID = __ENV.PRODUCT_ID || '550e8400-e29b-41d4-a716-446655440000';
27
28export function setup() {
29 // Login sebagai pre-seeded user untuk semua VUs
30 // (lebih realistis: setiap VU punya user sendiri)
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 // Idempotency key unik 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}Dengan memisahkan threshold per name, kita bisa langsung tahu tahap mana yang melampaui SLO — place order boleh sampai 1s P95, tapi get orders harus tetap di bawah 200ms.
19.04 k6 Spike Test
Selain beban bertahap, kita perlu menguji lonjakan mendadak untuk melihat apakah sistem pulih setelah spike. Konfigurasi ringkas berikut melompatkan beban dari 10 ke 500 VU dalam 10 detik, lalu mengembalikannya ke normal.
1// tests/load/spike_test.js
2// Test: apakah sistem recover dari spike traffic?
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'], // Boleh error 5% saat spike
14 'http_req_duration{name:list_products}': ['p(95)<2000'],
15 },
16};Threshold di sini sengaja lebih longgar (error 5% ditoleransi): tujuannya bukan zero error saat spike, melainkan memastikan sistem tidak stuck dan kembali sehat setelah beban turun.
19.05 Benchmark Tests
Load test mengukur sistem end-to-end; benchmark mengukur satu usecase secara mikro. Benchmark PlaceOrder berikut memakai mock repository dan b.RunParallel untuk mensimulasikan request konkuren tanpa menyentuh 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/opFlag -benchmem memunculkan B/op dan allocs/op — dua angka yang paling sering menjadi target optimasi karena alokasi berlebih membebani garbage collector.
19.06 Password Hashing Benchmark
bcrypt adalah bottleneck yang disengaja, dan benchmark ini memverifikasi biayanya secara eksplisit. Kita bandingkan cost 12 dan cost 10 untuk memahami trade-off keamanan versus throughput registrasi.
1// internal/usecase/auth/register_bench_test.go
2//go:build bench
3
4func BenchmarkRegisterUser_bcryptCost12(b *testing.B) {
5 // bcrypt adalah bottleneck yang disengaja - benchmark untuk 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 adalah sweet spot security vs performance.
23// Registration rate 4/s adalah acceptable untuk low-frequency endpoint.Kesimpulannya cost 12 hanya sanggup ~4 registrasi/detik, dan itu memang dapat diterima: registrasi adalah endpoint low-frequency, sementara proteksi brute force jauh lebih penting.
19.07 Database Query Benchmark
Benchmark repository mengukur query nyata terhadap PostgreSQL, bukan mock. Dua benchmark berikut membandingkan list produk tanpa search versus dengan full-text search agar dampak GIN index terlihat.
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: "sepatu lari", 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)Perbedaan 2.1ms versus 5.3ms menegaskan full-text search memang lebih mahal, tapi tetap terkendali karena GIN index sudah aktif — tanpa index, angkanya bisa puluhan kali lipat.
19.08 pprof CPU Profile Analysis
Setelah tahu angka agregat, pprof menunjukkan fungsi mana yang memakan CPU. Langkah-langkah berikut menjalankan load test ringan, mengambil CPU profile 30 detik, lalu menganalisisnya secara interaktif.
1# Langkah-langkah profiling:
2
3# 1. Jalankan load test ringan di background
4k6 run --vus=10 --duration=60s tests/load/place_order_flow.js &
5
6# 2. Ambil CPU profile (30 detik)
7curl -s http://localhost:6060/debug/pprof/profile?seconds=30 > cpu.prof
8
9# 3. Analisis interaktif
10go tool pprof -http=:8081 cpu.prof
11# Buka http://localhost:8081
12
13# Alternatif: text output
14go tool pprof cpu.prof
15> top15 # 15 fungsi dengan CPU terbesar
16> web # buka flame graph di browser
17> list placeOrder # lihat source code dengan anotasi
18
19# Typical findings di Santekno Shop:
20# 1. bcrypt.GenerateFromPassword: 65% CPU saat load test dengan registration
21# -> Expected! bcrypt cost 12 adalah by design
22# 2. json.Marshal: 12% CPU
23# -> Bisa di-optimize dengan encoding/json stream atau fastjson
24# 3. pgxpool.Query: 15% CPU
25# -> Perlu analisis query planTemuan tipikal mengonfirmasi hipotesis benchmark: bcrypt mendominasi saat ada registrasi, sementara json.Marshal dan query database adalah kandidat optimasi berikutnya.
19.09 Memory Profile Analysis
Selain CPU, kita perlu memastikan tidak ada memory leak atau goroutine leak. Perintah berikut mengambil heap profile, goroutine dump, dan trace scheduler untuk diperiksa.
1# Heap profile
2curl -s http://localhost:6060/debug/pprof/heap > heap.prof
3go tool pprof -http=:8082 heap.prof
4
5# Goroutine dump (untuk detect goroutine leak)
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 (lihat scheduler)
14curl -s http://localhost:6060/debug/pprof/trace?seconds=5 > trace.out
15go tool trace trace.outSinyal paling penting di sini adalah jumlah goroutine yang terus naik seiring waktu — itu tanda leak yang harus diinvestigasi sebelum masuk produksi.
19.10 Baseline Results: Expected Metrics
Semua pengukuran di atas berujung pada tabel baseline. Ringkasan berikut mencatat lingkungan test, latency per endpoint, dan urutan bottleneck yang teridentifikasi.
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 (sebelum 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 neededTabel inilah “angka nol” kita: setiap optimasi di artikel berikutnya akan dibandingkan terhadapnya untuk membuktikan dampak nyata.
19.11 EXPLAIN ANALYZE untuk PlaceOrder
Untuk memastikan query kunci memakai index, kita jalankan EXPLAIN ANALYZE. Tiga query di jalur PlaceOrder berikut kita periksa satu per satu.
1-- Analyze query yang paling sering di 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.2msKata kunci yang dicari adalah Index Scan, bukan Seq Scan. Selama semua query memakai index dan execution time di bawah 1ms, jalur PlaceOrder aman dari sisi database.
19.12 Identify dan Fix Bottleneck N+1
Bottleneck klasik di endpoint list adalah N+1 query. Contoh berikut menampilkan versi salah yang menembak satu query per order, lalu versi benar yang menariknya dalam satu batch.
1// BUG: N+1 query problem di GetOrders (tidak ada di kode kita, tapi 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! satu query per order
10 orders = append(orders, &Order{Items: items})
11 }
12}
13
14// RIGHT - single query dengan JOIN atau batch
15func (r *OrderRepository) ListByUserID(...) ([]*Order, int, error) {
16 // Ambil orders dulu
17 orders, _ := r.queryOrders(ctx, userID, page, limit)
18
19 // Ambil semua items dalam satu query
20 orderIDs := extractIDs(orders)
21 items, _ := r.queryItemsByOrderIDs(ctx, orderIDs) // satu query
22
23 // Map items ke orders
24 itemsByOrderID := groupByOrderID(items)
25 for _, o := range orders {
26 o.Items = itemsByOrderID[o.ID]
27 }
28 return orders, total, nil
29}Pola benar mengubah N+1 query menjadi 2 query tetap, berapa pun jumlah order — perbedaan yang menentukan saat pengguna punya ratusan pesanan.
19.13 Redis Cache Impact Measurement
Untuk membuktikan cache benar-benar berdampak, kita ukur dengan dan tanpa Redis. Dua run k6 berikut membandingkan cold cache versus warm cache pada endpoint list produk.
1# Ukur dampak cache dengan membandingkan:
2# Test A: Redis disabled (atau cache miss force)
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 productsAngka 45ms turun ke 8ms (5x lebih cepat) memberi justifikasi kuantitatif untuk menjaga cache tetap ada — bukan sekadar asumsi bahwa “cache pasti membantu”.
19.14 Load Test Data Preparation
Baseline hanya valid jika datanya realistis. Seed script berikut mengisi 1000 produk, satu user load test, dan alamat pengiriman mock sebelum k6 dijalankan.
1-- Seed script untuk load test
2-- Jalankan sebelum 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');Dengan 1000 produk, query plan, GIN index, dan cache hit rate mencerminkan kondisi produksi — sehingga baseline tidak bias oleh dataset yang terlalu kecil.
19.15 Performance Baseline Report
Hasil pengukuran perlu didokumentasikan dalam format yang bisa dibandingkan lintas waktu. Template report berikut mencatat konfigurasi, ringkasan hasil, bottleneck, dan status pass/fail terhadap 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 in scale)
313. Full-text search without cache: 45ms P95 (optimize Artikel 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 (Artikel 13 already implemented)
40-> Benchmark with 3 app replicas
41-> Load test Artikel 20 (AI features) to measure LLM overheadReport terstruktur seperti ini menjadi artefak yang bisa di-commit ke repo, sehingga siapa pun bisa membandingkan baseline lama dan baru tanpa menebak konteks.
19.16 Continuous Performance Testing
Baseline yang tidak dijaga akan basi. Workflow GitHub Actions berikut menjalankan load test mingguan dan menggagalkan build jika P95 melampaui ambang.
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.jsonDengan job terjadwal ini, regresi performa terdeteksi otomatis setiap minggu, bukan saat pengguna mengeluh di produksi.
19.17 Go Benchmark Comparison: Before/After
Untuk membandingkan hasil optimasi secara statistik, kita pakai benchstat. Rangkaian perintah berikut menyimpan baseline, menjalankan benchmark setelah optimasi, lalu menghitung delta beserta p-value-nya.
1# Simpan benchmark baseline
2go test -bench=. -benchmem -tags=bench ./internal/... > benchmark-baseline.txt
3
4# Setelah optimization (contoh: cache + query tuning):
5go test -bench=. -benchmem -tags=bench ./internal/... > benchmark-after.txt
6
7# Compare dengan 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)Nilai p di bawah 0.05 memastikan perbaikan itu signifikan secara statistik, bukan sekadar noise pengukuran — inilah pembeda klaim optimasi yang serius.
19.18 Goroutine Leak Detection
Goroutine leak sering luput karena tidak langsung membuat sistem crash. Helper VerifyNoLeak berikut membandingkan jumlah goroutine sebelum dan sesudah menjalankan fungsi target.
1// testutil/goroutine/leak.go
2
3package goroutine
4
5import (
6 "runtime"
7 "testing"
8 "time"
9)
10
11// VerifyNoLeak: assert tidak ada goroutine leak setelah test
12func VerifyNoLeak(t *testing.T, fn func()) {
13 t.Helper()
14 before := runtime.NumGoroutine()
15 fn()
16
17 // Beri waktu goroutine cleanup
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 handler yang spawn goroutine
35 h.PlaceOrder(ctx, req)
36 })
37}Helper ini memberi jeda cleanup sebelum menilai, sehingga tidak salah menuduh goroutine yang memang sedang dalam proses berhenti sebagai leak.
19.19 Profiling Checklist Production
Sebelum setiap deploy produksi, ada checklist profiling yang harus lolos. Daftar berikut merangkum ambang CPU, memory, goroutine, dan database yang wajib diverifikasi.
1Before each production deploy, verify:
2
3CPU Profile:
4 [ ] Tidak ada unexpected hotspot (> 20% CPU single function selain bcrypt)
5 [ ] GC pause < 10ms P99
6 [ ] json.Marshal tidak dominate (pertanda banyak allocations)
7
8Memory Profile:
9 [ ] Heap growth rate < 5MB per minute under steady load
10 [ ] Tidak ada memory leak (heap grows tanpa bound)
11 [ ] Buffer pool reuse rate > 80%
12
13Goroutines:
14 [ ] Goroutine count stabil (tidak terus naik)
15 [ ] Tidak ada goroutine blocked > 30 detik
16
17DB:
18 [ ] Connection pool usage < 80% at peak load
19 [ ] Semua query menggunakan index (tidak full table scan)
20 [ ] Transaction duration P95 < 100msChecklist ini mengubah profiling dari aktivitas ad-hoc menjadi gate rilis yang konsisten, sehingga regresi tertangkap sebelum menyentuh pengguna.
19.20 Ringkasan: Performance Baseline Established
Santekno Shop kini punya performance baseline yang measurable dan reproducible. Rekap berikut menutup semua yang sudah kita bangun di artikel ini.
- k6 Load Tests: auth flow, order flow, spike test — semua dengan threshold yang link ke SLO.
- Benchmarks: usecase benchmarks (mock), repository benchmarks (real DB), password hashing benchmarks.
- pprof: CPU dan memory profiling workflow yang bisa direproduksi.
- Baseline metrics: P95 latency, throughput, resource utilization per endpoint — semua terdokumentasi.
- Bottlenecks identified: bcrypt (by design), DB transaction PlaceOrder (acceptable), full-text search (dimitigasi oleh cache).
Dengan baseline yang solid, setiap perubahan berikutnya — termasuk penambahan fitur AI di Topik 6 — bisa diukur dampak performanya secara persis, bukan ditebak.