| 1 |
// Load test program for ntfy staging server. |
| 2 |
// Replicates production traffic patterns derived from access.log analysis. |
| 3 |
// |
| 4 |
// Traffic profile (from ~5M requests over 20 hours): |
| 5 |
// ~71 req/sec average, ~4,300 req/min |
| 6 |
// 49.6% poll requests (GET /TOPIC/json?poll=1&since=ID) |
| 7 |
// 21.4% publish POST (POST /TOPIC with small body) |
| 8 |
// 6.2% subscribe stream (GET /TOPIC/json?since=X, long-lived) |
| 9 |
// 4.1% config check (GET /v1/config) |
| 10 |
// 2.3% other topic GET (GET /TOPIC) |
| 11 |
// 2.2% account check (GET /v1/account) |
| 12 |
// 1.9% websocket sub (GET /TOPIC/ws?since=X) |
| 13 |
// 1.5% publish PUT (PUT /TOPIC with small body) |
| 14 |
// 1.5% raw subscribe (GET /TOPIC/raw?since=X) |
| 15 |
// 1.1% json subscribe (GET /TOPIC/json, no since) |
| 16 |
// 0.7% SSE subscribe (GET /TOPIC/sse?since=X) |
| 17 |
// remaining: static, PATCH, OPTIONS, etc. (omitted) |
| 18 |
|
| 19 |
package main |
| 20 |
|
| 21 |
import ( |
| 22 |
"context" |
| 23 |
"crypto/rand" |
| 24 |
"encoding/hex" |
| 25 |
"flag" |
| 26 |
"fmt" |
| 27 |
"io" |
| 28 |
|
| 29 |
"math/big" |
| 30 |
mrand "math/rand" |
| 31 |
"net/http" |
| 32 |
"os" |
| 33 |
"os/signal" |
| 34 |
"strings" |
| 35 |
"sync" |
| 36 |
"sync/atomic" |
| 37 |
"time" |
| 38 |
|
| 39 |
"github.com/gorilla/websocket" |
| 40 |
) |
| 41 |
|
| 42 |
var ( |
| 43 |
baseURL string |
| 44 |
username string |
| 45 |
password string |
| 46 |
rps float64 |
| 47 |
scale float64 |
| 48 |
numTopics int |
| 49 |
subStreams int |
| 50 |
wsStreams int |
| 51 |
sseStreams int |
| 52 |
rawStreams int |
| 53 |
duration time.Duration |
| 54 |
|
| 55 |
totalRequests atomic.Int64 |
| 56 |
totalErrors atomic.Int64 |
| 57 |
activeStreams atomic.Int64 |
| 58 |
|
| 59 |
// Error tracking by category |
| 60 |
errMu sync.Mutex |
| 61 |
recentErrors []string // last N unique error messages |
| 62 |
errorCounts = make(map[string]int64) |
| 63 |
) |
| 64 |
|
| 65 |
func main() { |
| 66 |
flag.StringVar(&baseURL, "url", "https://staging.ntfy.sh", "Base URL of ntfy server") |
| 67 |
flag.StringVar(&username, "user", "", "Username for authentication") |
| 68 |
flag.StringVar(&password, "pass", "", "Password for authentication") |
| 69 |
flag.Float64Var(&rps, "rps", 71, "Target requests per second (default: prod average)") |
| 70 |
flag.Float64Var(&scale, "scale", 1.0, "Scale factor for all load (0.5 = half load, 2.0 = double)") |
| 71 |
flag.IntVar(&numTopics, "topics", 500, "Number of unique topics to use") |
| 72 |
flag.IntVar(&subStreams, "sub-streams", 200, "Number of concurrent JSON streaming subscriptions") |
| 73 |
flag.IntVar(&wsStreams, "ws-streams", 50, "Number of concurrent WebSocket subscriptions") |
| 74 |
flag.IntVar(&sseStreams, "sse-streams", 20, "Number of concurrent SSE subscriptions") |
| 75 |
flag.IntVar(&rawStreams, "raw-streams", 30, "Number of concurrent raw subscriptions") |
| 76 |
flag.DurationVar(&duration, "duration", 10*time.Minute, "Test duration") |
| 77 |
flag.Parse() |
| 78 |
|
| 79 |
rps *= scale |
| 80 |
subStreams = int(float64(subStreams) * scale) |
| 81 |
wsStreams = int(float64(wsStreams) * scale) |
| 82 |
sseStreams = int(float64(sseStreams) * scale) |
| 83 |
rawStreams = int(float64(rawStreams) * scale) |
| 84 |
|
| 85 |
topics := generateTopics(numTopics) |
| 86 |
|
| 87 |
fmt.Printf("ntfy load test\n") |
| 88 |
fmt.Printf(" Target: %s\n", baseURL) |
| 89 |
fmt.Printf(" RPS: %.1f\n", rps) |
| 90 |
fmt.Printf(" Scale: %.1fx\n", scale) |
| 91 |
fmt.Printf(" Topics: %d\n", numTopics) |
| 92 |
fmt.Printf(" Sub streams: %d json, %d ws, %d sse, %d raw\n", subStreams, wsStreams, sseStreams, rawStreams) |
| 93 |
fmt.Printf(" Duration: %s\n", duration) |
| 94 |
fmt.Println() |
| 95 |
|
| 96 |
ctx, cancel := context.WithTimeout(context.Background(), duration) |
| 97 |
defer cancel() |
| 98 |
|
| 99 |
// Also handle Ctrl+C |
| 100 |
sigCtx, sigCancel := signal.NotifyContext(ctx, os.Interrupt) |
| 101 |
defer sigCancel() |
| 102 |
ctx = sigCtx |
| 103 |
|
| 104 |
client := &http.Client{ |
| 105 |
Timeout: 10 * time.Second, |
| 106 |
Transport: &http.Transport{ |
| 107 |
MaxIdleConns: 1000, |
| 108 |
MaxIdleConnsPerHost: 1000, |
| 109 |
IdleConnTimeout: 90 * time.Second, |
| 110 |
}, |
| 111 |
} |
| 112 |
|
| 113 |
// Long-lived streaming client (no timeout) |
| 114 |
streamClient := &http.Client{ |
| 115 |
Timeout: 0, |
| 116 |
Transport: &http.Transport{ |
| 117 |
MaxIdleConns: 500, |
| 118 |
MaxIdleConnsPerHost: 500, |
| 119 |
IdleConnTimeout: 0, |
| 120 |
}, |
| 121 |
} |
| 122 |
|
| 123 |
var wg sync.WaitGroup |
| 124 |
|
| 125 |
// Start long-lived streaming subscriptions |
| 126 |
for i := 0; i < subStreams; i++ { |
| 127 |
wg.Add(1) |
| 128 |
go func() { |
| 129 |
defer wg.Done() |
| 130 |
streamSubscription(ctx, streamClient, topics, "json") |
| 131 |
}() |
| 132 |
} |
| 133 |
for i := 0; i < wsStreams; i++ { |
| 134 |
wg.Add(1) |
| 135 |
go func() { |
| 136 |
defer wg.Done() |
| 137 |
wsSubscription(ctx, topics) |
| 138 |
}() |
| 139 |
} |
| 140 |
for i := 0; i < sseStreams; i++ { |
| 141 |
wg.Add(1) |
| 142 |
go func() { |
| 143 |
defer wg.Done() |
| 144 |
streamSubscription(ctx, streamClient, topics, "sse") |
| 145 |
}() |
| 146 |
} |
| 147 |
for i := 0; i < rawStreams; i++ { |
| 148 |
wg.Add(1) |
| 149 |
go func() { |
| 150 |
defer wg.Done() |
| 151 |
streamSubscription(ctx, streamClient, topics, "raw") |
| 152 |
}() |
| 153 |
} |
| 154 |
|
| 155 |
// Start request generators based on traffic weights |
| 156 |
// Weights from log analysis (normalized to sum ~100): |
| 157 |
// poll=49.6, publish_post=21.4, config=4.1, other_get=2.3, account=2.2, publish_put=1.5 |
| 158 |
// Total short-lived weight ≈ 81.1 |
| 159 |
type requestType struct { |
| 160 |
name string |
| 161 |
weight float64 |
| 162 |
fn func(ctx context.Context, client *http.Client, topics []string) |
| 163 |
} |
| 164 |
|
| 165 |
types := []requestType{ |
| 166 |
{"poll", 49.6, doPoll}, |
| 167 |
{"publish_post", 21.4, doPublishPost}, |
| 168 |
{"config", 4.1, doConfig}, |
| 169 |
{"other_get", 2.3, doOtherGet}, |
| 170 |
{"account", 2.2, doAccountCheck}, |
| 171 |
{"publish_put", 1.5, doPublishPut}, |
| 172 |
} |
| 173 |
|
| 174 |
totalWeight := 0.0 |
| 175 |
for _, t := range types { |
| 176 |
totalWeight += t.weight |
| 177 |
} |
| 178 |
|
| 179 |
for _, t := range types { |
| 180 |
t := t |
| 181 |
typeRPS := rps * (t.weight / totalWeight) |
| 182 |
if typeRPS < 0.1 { |
| 183 |
continue |
| 184 |
} |
| 185 |
wg.Add(1) |
| 186 |
go func() { |
| 187 |
defer wg.Done() |
| 188 |
runAtRate(ctx, typeRPS, func() { |
| 189 |
t.fn(ctx, client, topics) |
| 190 |
}) |
| 191 |
}() |
| 192 |
} |
| 193 |
|
| 194 |
// Stats reporter |
| 195 |
wg.Add(1) |
| 196 |
go func() { |
| 197 |
defer wg.Done() |
| 198 |
reportStats(ctx) |
| 199 |
}() |
| 200 |
|
| 201 |
wg.Wait() |
| 202 |
fmt.Printf("\nDone. Total requests: %d, errors: %d\n", totalRequests.Load(), totalErrors.Load()) |
| 203 |
} |
| 204 |
|
| 205 |
func trackError(category string, err error) { |
| 206 |
totalErrors.Add(1) |
| 207 |
key := fmt.Sprintf("%s: %s", category, truncateErr(err)) |
| 208 |
errMu.Lock() |
| 209 |
errorCounts[key]++ |
| 210 |
errMu.Unlock() |
| 211 |
} |
| 212 |
|
| 213 |
func trackErrorMsg(category string, msg string) { |
| 214 |
totalErrors.Add(1) |
| 215 |
key := fmt.Sprintf("%s: %s", category, msg) |
| 216 |
errMu.Lock() |
| 217 |
errorCounts[key]++ |
| 218 |
errMu.Unlock() |
| 219 |
} |
| 220 |
|
| 221 |
func truncateErr(err error) string { |
| 222 |
s := err.Error() |
| 223 |
if len(s) > 120 { |
| 224 |
s = s[:120] + "..." |
| 225 |
} |
| 226 |
return s |
| 227 |
} |
| 228 |
|
| 229 |
func setAuth(req *http.Request) { |
| 230 |
if username != "" && password != "" { |
| 231 |
req.SetBasicAuth(username, password) |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
func generateTopics(n int) []string { |
| 236 |
topics := make([]string, n) |
| 237 |
for i := 0; i < n; i++ { |
| 238 |
b := make([]byte, 8) |
| 239 |
rand.Read(b) |
| 240 |
topics[i] = "loadtest-" + hex.EncodeToString(b) |
| 241 |
} |
| 242 |
return topics |
| 243 |
} |
| 244 |
|
| 245 |
func pickTopic(topics []string) string { |
| 246 |
n, _ := rand.Int(rand.Reader, big.NewInt(int64(len(topics)))) |
| 247 |
return topics[n.Int64()] |
| 248 |
} |
| 249 |
|
| 250 |
func randomSince() string { |
| 251 |
b := make([]byte, 6) |
| 252 |
rand.Read(b) |
| 253 |
return hex.EncodeToString(b) |
| 254 |
} |
| 255 |
|
| 256 |
func randomMessage() string { |
| 257 |
messages := []string{ |
| 258 |
"Test notification", |
| 259 |
"Server backup completed successfully", |
| 260 |
"Deployment finished", |
| 261 |
"Alert: disk usage above 80%", |
| 262 |
"Build #1234 passed", |
| 263 |
"New order received", |
| 264 |
"Temperature sensor reading: 72F", |
| 265 |
"Cron job completed", |
| 266 |
} |
| 267 |
return messages[mrand.Intn(len(messages))] |
| 268 |
} |
| 269 |
|
| 270 |
// runAtRate executes fn at approximately the given rate per second |
| 271 |
func runAtRate(ctx context.Context, rate float64, fn func()) { |
| 272 |
interval := time.Duration(float64(time.Second) / rate) |
| 273 |
ticker := time.NewTicker(interval) |
| 274 |
defer ticker.Stop() |
| 275 |
|
| 276 |
for { |
| 277 |
select { |
| 278 |
case <-ctx.Done(): |
| 279 |
return |
| 280 |
case <-ticker.C: |
| 281 |
go fn() |
| 282 |
} |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
// --- Short-lived request types --- |
| 287 |
|
| 288 |
func doPoll(ctx context.Context, client *http.Client, topics []string) { |
| 289 |
topic := pickTopic(topics) |
| 290 |
url := fmt.Sprintf("%s/%s/json?poll=1&since=%s", baseURL, topic, randomSince()) |
| 291 |
doGet(ctx, client, url) |
| 292 |
} |
| 293 |
|
| 294 |
func doPublishPost(ctx context.Context, client *http.Client, topics []string) { |
| 295 |
topic := pickTopic(topics) |
| 296 |
url := fmt.Sprintf("%s/%s", baseURL, topic) |
| 297 |
req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(randomMessage())) |
| 298 |
if err != nil { |
| 299 |
trackError("publish_post_req", err) |
| 300 |
return |
| 301 |
} |
| 302 |
setAuth(req) |
| 303 |
// Some messages have titles/priorities like real traffic |
| 304 |
if mrand.Float32() < 0.3 { |
| 305 |
req.Header.Set("X-Title", "Load Test") |
| 306 |
} |
| 307 |
if mrand.Float32() < 0.1 { |
| 308 |
req.Header.Set("X-Priority", fmt.Sprintf("%d", mrand.Intn(5)+1)) |
| 309 |
} |
| 310 |
resp, err := client.Do(req) |
| 311 |
totalRequests.Add(1) |
| 312 |
if err != nil { |
| 313 |
trackError("publish_post", err) |
| 314 |
return |
| 315 |
} |
| 316 |
io.Copy(io.Discard, resp.Body) |
| 317 |
resp.Body.Close() |
| 318 |
if resp.StatusCode >= 400 { |
| 319 |
trackErrorMsg("publish_post_http", fmt.Sprintf("status %d", resp.StatusCode)) |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
func doPublishPut(ctx context.Context, client *http.Client, topics []string) { |
| 324 |
topic := pickTopic(topics) |
| 325 |
url := fmt.Sprintf("%s/%s", baseURL, topic) |
| 326 |
req, err := http.NewRequestWithContext(ctx, "PUT", url, strings.NewReader(randomMessage())) |
| 327 |
if err != nil { |
| 328 |
trackError("publish_put_req", err) |
| 329 |
return |
| 330 |
} |
| 331 |
setAuth(req) |
| 332 |
resp, err := client.Do(req) |
| 333 |
totalRequests.Add(1) |
| 334 |
if err != nil { |
| 335 |
trackError("publish_put", err) |
| 336 |
return |
| 337 |
} |
| 338 |
io.Copy(io.Discard, resp.Body) |
| 339 |
resp.Body.Close() |
| 340 |
if resp.StatusCode >= 400 { |
| 341 |
trackErrorMsg("publish_put_http", fmt.Sprintf("status %d", resp.StatusCode)) |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
func doConfig(ctx context.Context, client *http.Client, topics []string) { |
| 346 |
url := fmt.Sprintf("%s/v1/config", baseURL) |
| 347 |
doGet(ctx, client, url) |
| 348 |
} |
| 349 |
|
| 350 |
func doAccountCheck(ctx context.Context, client *http.Client, topics []string) { |
| 351 |
url := fmt.Sprintf("%s/v1/account", baseURL) |
| 352 |
doGet(ctx, client, url) |
| 353 |
} |
| 354 |
|
| 355 |
func doOtherGet(ctx context.Context, client *http.Client, topics []string) { |
| 356 |
topic := pickTopic(topics) |
| 357 |
url := fmt.Sprintf("%s/%s", baseURL, topic) |
| 358 |
doGet(ctx, client, url) |
| 359 |
} |
| 360 |
|
| 361 |
func doGet(ctx context.Context, client *http.Client, url string) { |
| 362 |
req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 363 |
if err != nil { |
| 364 |
trackError("get_req", err) |
| 365 |
return |
| 366 |
} |
| 367 |
setAuth(req) |
| 368 |
resp, err := client.Do(req) |
| 369 |
totalRequests.Add(1) |
| 370 |
if err != nil { |
| 371 |
trackError("get", err) |
| 372 |
return |
| 373 |
} |
| 374 |
io.Copy(io.Discard, resp.Body) |
| 375 |
resp.Body.Close() |
| 376 |
if resp.StatusCode >= 400 { |
| 377 |
trackErrorMsg("get_http", fmt.Sprintf("status %d for %s", resp.StatusCode, url)) |
| 378 |
} |
| 379 |
} |
| 380 |
|
| 381 |
// --- Long-lived streaming subscriptions --- |
| 382 |
|
| 383 |
func streamSubscription(ctx context.Context, client *http.Client, topics []string, format string) { |
| 384 |
for { |
| 385 |
if ctx.Err() != nil { |
| 386 |
return |
| 387 |
} |
| 388 |
topic := pickTopic(topics) |
| 389 |
url := fmt.Sprintf("%s/%s/%s?since=all", baseURL, topic, format) |
| 390 |
req, err := http.NewRequestWithContext(ctx, "GET", url, nil) |
| 391 |
if err != nil { |
| 392 |
time.Sleep(time.Second) |
| 393 |
continue |
| 394 |
} |
| 395 |
setAuth(req) |
| 396 |
activeStreams.Add(1) |
| 397 |
resp, err := client.Do(req) |
| 398 |
if err != nil { |
| 399 |
activeStreams.Add(-1) |
| 400 |
if ctx.Err() == nil { |
| 401 |
trackError("stream_"+format+"_connect", err) |
| 402 |
} |
| 403 |
time.Sleep(time.Second) |
| 404 |
continue |
| 405 |
} |
| 406 |
if resp.StatusCode >= 400 { |
| 407 |
trackErrorMsg("stream_"+format+"_http", fmt.Sprintf("status %d", resp.StatusCode)) |
| 408 |
resp.Body.Close() |
| 409 |
activeStreams.Add(-1) |
| 410 |
time.Sleep(time.Second) |
| 411 |
continue |
| 412 |
} |
| 413 |
// Read from stream until context cancelled or connection drops |
| 414 |
buf := make([]byte, 4096) |
| 415 |
for { |
| 416 |
_, err := resp.Body.Read(buf) |
| 417 |
if err != nil { |
| 418 |
if ctx.Err() == nil { |
| 419 |
trackError("stream_"+format+"_read", err) |
| 420 |
} |
| 421 |
break |
| 422 |
} |
| 423 |
} |
| 424 |
resp.Body.Close() |
| 425 |
activeStreams.Add(-1) |
| 426 |
// Reconnect with small delay (like real clients do) |
| 427 |
select { |
| 428 |
case <-ctx.Done(): |
| 429 |
return |
| 430 |
case <-time.After(time.Duration(mrand.Intn(3000)) * time.Millisecond): |
| 431 |
} |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
func wsSubscription(ctx context.Context, topics []string) { |
| 436 |
wsURL := strings.Replace(baseURL, "https://", "wss://", 1) |
| 437 |
wsURL = strings.Replace(wsURL, "http://", "ws://", 1) |
| 438 |
|
| 439 |
for { |
| 440 |
if ctx.Err() != nil { |
| 441 |
return |
| 442 |
} |
| 443 |
topic := pickTopic(topics) |
| 444 |
url := fmt.Sprintf("%s/%s/ws?since=all", wsURL, topic) |
| 445 |
|
| 446 |
dialer := websocket.Dialer{ |
| 447 |
HandshakeTimeout: 10 * time.Second, |
| 448 |
} |
| 449 |
var wsHeader http.Header |
| 450 |
if username != "" && password != "" { |
| 451 |
wsHeader = http.Header{} |
| 452 |
req, _ := http.NewRequest("GET", url, nil) |
| 453 |
req.SetBasicAuth(username, password) |
| 454 |
wsHeader.Set("Authorization", req.Header.Get("Authorization")) |
| 455 |
} |
| 456 |
activeStreams.Add(1) |
| 457 |
conn, _, err := dialer.DialContext(ctx, url, wsHeader) |
| 458 |
if err != nil { |
| 459 |
activeStreams.Add(-1) |
| 460 |
if ctx.Err() == nil { |
| 461 |
trackError("ws_connect", err) |
| 462 |
} |
| 463 |
time.Sleep(time.Second) |
| 464 |
continue |
| 465 |
} |
| 466 |
|
| 467 |
// Read messages until context cancelled or error |
| 468 |
done := make(chan struct{}) |
| 469 |
go func() { |
| 470 |
defer close(done) |
| 471 |
for { |
| 472 |
conn.SetReadDeadline(time.Now().Add(5 * time.Minute)) |
| 473 |
_, _, err := conn.ReadMessage() |
| 474 |
if err != nil { |
| 475 |
return |
| 476 |
} |
| 477 |
} |
| 478 |
}() |
| 479 |
|
| 480 |
select { |
| 481 |
case <-ctx.Done(): |
| 482 |
conn.Close() |
| 483 |
activeStreams.Add(-1) |
| 484 |
return |
| 485 |
case <-done: |
| 486 |
conn.Close() |
| 487 |
activeStreams.Add(-1) |
| 488 |
} |
| 489 |
|
| 490 |
select { |
| 491 |
case <-ctx.Done(): |
| 492 |
return |
| 493 |
case <-time.After(time.Duration(mrand.Intn(3000)) * time.Millisecond): |
| 494 |
} |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
func reportStats(ctx context.Context) { |
| 499 |
ticker := time.NewTicker(5 * time.Second) |
| 500 |
defer ticker.Stop() |
| 501 |
|
| 502 |
var lastRequests, lastErrors int64 |
| 503 |
lastTime := time.Now() |
| 504 |
reportCount := 0 |
| 505 |
|
| 506 |
for { |
| 507 |
select { |
| 508 |
case <-ctx.Done(): |
| 509 |
return |
| 510 |
case <-ticker.C: |
| 511 |
now := time.Now() |
| 512 |
currentRequests := totalRequests.Load() |
| 513 |
currentErrors := totalErrors.Load() |
| 514 |
elapsed := now.Sub(lastTime).Seconds() |
| 515 |
currentRPS := float64(currentRequests-lastRequests) / elapsed |
| 516 |
errorRate := float64(currentErrors-lastErrors) / elapsed |
| 517 |
|
| 518 |
fmt.Printf("[%s] rps=%.1f err/s=%.1f total=%d errors=%d streams=%d\n", |
| 519 |
now.Format("15:04:05"), |
| 520 |
currentRPS, |
| 521 |
errorRate, |
| 522 |
currentRequests, |
| 523 |
currentErrors, |
| 524 |
activeStreams.Load(), |
| 525 |
) |
| 526 |
|
| 527 |
// Print error breakdown every 30 seconds |
| 528 |
reportCount++ |
| 529 |
if reportCount%6 == 0 && currentErrors > 0 { |
| 530 |
errMu.Lock() |
| 531 |
fmt.Printf(" Error breakdown:\n") |
| 532 |
for k, v := range errorCounts { |
| 533 |
fmt.Printf(" %s: %d\n", k, v) |
| 534 |
} |
| 535 |
errMu.Unlock() |
| 536 |
} |
| 537 |
|
| 538 |
lastRequests = currentRequests |
| 539 |
lastErrors = currentErrors |
| 540 |
lastTime = now |
| 541 |
} |
| 542 |
} |
| 543 |
} |