DocsGuidesPerformance Tuning

Performance Tuning

Optimize TopGun for your specific workload: high throughput, low latency, or balanced production use.

Performance Benchmarks

Measured Performance (single node)

33,000+
ops/sec sustained throughput
100
concurrent clients (tested)
<15ms
p50 write latency

Benchmarks run with native MessagePack harness (msgpackr) on a single server node. Results measured under sustained load with 100 concurrent connections. Optimizations include msgpackr for 2x faster serialization, native xxHash64 for Merkle tree hashing, and subscription-based routing.

Understanding the Optimizations

TopGun includes several performance optimizations inspired by proven patterns from high-performance distributed systems:

Subscription-Based Routing

Events are only sent to clients with active subscriptions, eliminating unnecessary broadcasts and reducing network traffic.

Bounded Event Queue

A capacity-limited queue protects against OOM under load spikes. Events are rejected rather than accumulating unbounded.

Backpressure Regulation

Periodic synchronous processing prevents async operation buildup and ensures consistent latency under load.

Write Coalescing

Multiple small messages are batched into single syscalls, dramatically reducing kernel overhead at high throughput.

Tuning for High Throughput

For 100+ concurrent clients with heavy write loads.

Use these settings when your priority is maximizing events per second:

High Throughput Configuration
import { ServerCoordinator } from '@topgunbuild/server';

const server = new ServerCoordinator({
  port: 8080,
  nodeId: 'prod-node-1',

  // High throughput settings
  eventQueueCapacity: 50000,        // Larger queue for bursts
  eventStripeCount: 8,              // More parallel processing
  backpressureSyncFrequency: 200,   // Less frequent sync
  writeCoalescingMaxDelayMs: 10,    // Batch more writes
  writeCoalescingMaxBatch: 200,     // Larger batches

  // Connection scaling
  maxConnections: 50000,
  wsBacklog: 1024,
  maxConnectionsPerSecond: 500,
});

When to Adjust

SettingIncrease WhenDecrease When
eventQueueCapacitySeeing queue_rejected metricsMemory constrained
eventStripeCountCPU has many cores, queue contentionFew cores, diminishing returns
backpressureSyncFrequencyThroughput is priority over latencyLatency spikes are unacceptable
writeCoalescingMaxDelayMsNetwork is bottleneckReal-time delivery needed

Tuning for Low Latency

For real-time applications where every millisecond matters.

Use these settings for gaming, live collaboration, or trading applications:

Low Latency Configuration
import { ServerCoordinator } from '@topgunbuild/server';

const server = new ServerCoordinator({
  port: 8080,
  nodeId: 'realtime-node-1',

  // Low latency settings
  writeCoalescingEnabled: false,    // Disable batching for instant delivery
  // OR tune for minimal delay:
  // writeCoalescingMaxDelayMs: 1,  // 1ms max delay
  // writeCoalescingMaxBatch: 10,   // Small batches

  backpressureSyncFrequency: 50,    // More frequent sync
  eventStripeCount: 4,              // Balanced parallelism
});

Trade-off Warning

Disabling write coalescing increases syscall overhead significantly. Only disable when sub-millisecond latency is critical and you have sufficient CPU headroom.

Latency vs Throughput Trade-offs

writeCoalescingMaxDelayMsLatencyThroughputUse Case
Disabled (false)~0ms addedLowerLive gaming, trading
1ms~1ms addedMediumLive collaboration
5ms (default)~5ms addedHighGeneral purpose
10-20ms~10-20ms addedMaximumBatch processing

Balanced Production Settings

Recommended starting point for most production deployments.
Production Configuration
import { ServerCoordinator } from '@topgunbuild/server';

const server = new ServerCoordinator({
  port: 8080,
  nodeId: process.env.NODE_ID || 'prod-node-1',

  // Balanced production settings
  wsBacklog: 511,
  maxConnections: 10000,
  eventQueueCapacity: 50000,
  eventStripeCount: 4,

  // Backpressure tuning
  backpressureEnabled: true,
  backpressureSyncFrequency: 100,
  backpressureMaxPending: 2000,

  // Write coalescing (balanced)
  writeCoalescingEnabled: true,
  writeCoalescingMaxDelayMs: 5,
  writeCoalescingMaxBatch: 100,

  // Rate limiting for DDoS protection
  rateLimitingEnabled: true,
  maxConnectionsPerSecond: 200,
  maxPendingConnections: 2000,
});

Monitoring Performance

Key metrics to monitor for performance tuning.

Critical Metrics

MetricHealthy RangeAction if Exceeded
topgun_event_queue_size<80% of capacityIncrease eventQueueCapacity or add nodes
topgun_event_queue_rejected_total0Urgent: queue is full, events being dropped
topgun_backpressure_timeouts_total0Increase backpressureBackoffMs or reduce load
topgun_backpressure_pending_ops<80% of maxPendingIncrease backpressureMaxPending
topgun_connections_rejected_totalNear 0Increase rate limits or investigate DDoS

Grafana Dashboard Queries

PromQL Queries
# Queue utilization (should stay below 80%)
topgun_event_queue_size / topgun_event_queue_capacity * 100

# Connection rejection rate (should be near 0)
rate(topgun_connections_rejected_total[5m])

# Backpressure timeout rate (alert if > 0)
rate(topgun_backpressure_timeouts_total[5m])

# Event throughput
rate(topgun_events_routed_total[5m])

# Average subscribers per event
topgun_subscribers_per_event{quantile="0.5"}
Alert NameConditionSeverity
EventQueueFullrate(topgun_event_queue_rejected_total[5m]) > 0Critical
BackpressureTimeoutrate(topgun_backpressure_timeouts_total[5m]) > 0Critical
HighQueueUtilizationtopgun_event_queue_size / capacity > 0.8Warning
ConnectionRateLimitHitrate(topgun_connections_rejected_total[5m]) > 10Warning

OS-Level Tuning

Linux kernel parameters for high-connection workloads.

For production servers handling thousands of connections, tune the operating system:

Linux Sysctl Settings

Linux Kernel Tuning
# Increase socket backlog
sudo sysctl -w net.core.somaxconn=65535
sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535

# Increase file descriptor limits
ulimit -n 65535

# Enable TCP keepalive tuning
sudo sysctl -w net.ipv4.tcp_keepalive_time=60
sudo sysctl -w net.ipv4.tcp_keepalive_intvl=10
sudo sysctl -w net.ipv4.tcp_keepalive_probes=6

# Persist settings in /etc/sysctl.conf
cat >> /etc/sysctl.conf << EOF
net.core.somaxconn=65535
net.ipv4.tcp_max_syn_backlog=65535
net.ipv4.tcp_keepalive_time=60
net.ipv4.tcp_keepalive_intvl=10
net.ipv4.tcp_keepalive_probes=6
EOF

File Descriptor Limits

/etc/security/limits.conf
# /etc/security/limits.conf
topgun soft nofile 65535
topgun hard nofile 65535
topgun soft nproc 65535
topgun hard nproc 65535

Docker/Kubernetes Note

When running in containers, ensure the host has these settings applied. You may also need to set ulimits in your Docker Compose or Kubernetes pod spec.

Quick Reference

High Throughput

  • eventQueueCapacity: 50000+
  • eventStripeCount: 8
  • writeCoalescingMaxDelayMs: 10-20
  • backpressureSyncFrequency: 200

Low Latency

  • writeCoalescingEnabled: false
  • OR writeCoalescingMaxDelayMs: 1
  • backpressureSyncFrequency: 50
  • eventStripeCount: 4

Balanced

  • Use defaults
  • eventQueueCapacity: 10000-50000
  • writeCoalescingMaxDelayMs: 5
  • backpressureSyncFrequency: 100