Server API
The ServerCoordinator is the core of the TopGun backend. It manages client connections,
synchronization logic, clustering, and security enforcement.
Configuration
interface ServerCoordinatorConfigParameters
portnumber. Port to listen on for WebSocket connections.storage?IServerStorage. Backend storage adapter. Available adapters: PostgresAdapter (production), MemoryServerAdapter (testing). If omitted, runs in-memory.securityPolicies?PermissionPolicy[]. List of RBAC policies. See RBAC Guide.clusterPort?number. Port for inter-node communication.peers?string[]. List of initial peer addresses for clustering (e.g., ['node2:8000']).tls?TLSConfig. TLS configuration for client-facing connections (HTTPS/WSS). See TLS Configuration below.clusterTls?ClusterTLSConfig. TLS configuration for inter-node cluster communication. Supports mTLS.
Connection Scaling Options
Configure connection limits and WebSocket parameters for high-load scenarios.
Connection ScalingParameters
wsBacklog?number. TCP backlog for pending connections. Increase for high connection rates. Default: 511wsCompression?boolean. Enable WebSocket per-message compression. Disabled by default for CPU savings. Default: falsewsMaxPayload?number. Maximum WebSocket payload size in bytes. Default: 67108864 (64MB)maxConnections?number. Maximum concurrent client connections. Default: 10000serverTimeout?number. Server timeout in milliseconds. Default: 120000 (2 minutes)keepAliveTimeout?number. Keep-alive timeout in milliseconds. Default: 5000headersTimeout?number. Headers timeout in milliseconds. Default: 60000
Event Queue Options
Configure the bounded event queue for backpressure and memory protection.
Event QueueParameters
eventQueueCapacity?number. Maximum events in queue. Protects against OOM under load. Default: 10000eventStripeCount?number. Number of striped queues for parallel processing. Default: 4
Backpressure Options
Control backpressure behavior for async operation management.
BackpressureParameters
backpressureEnabled?boolean. Enable backpressure mechanism. Default: truebackpressureSyncFrequency?number. Force synchronous processing every N operations. Lower values reduce latency spikes. Default: 100backpressureMaxPending?number. Maximum pending async operations before blocking. Default: 1000backpressureBackoffMs?number. Backoff timeout in milliseconds when at capacity. Default: 5000
Write Coalescing Options
Batch WebSocket writes to reduce syscalls and improve throughput.
Write CoalescingParameters
writeCoalescingEnabled?boolean. Enable write batching. Disable for lowest latency real-time apps. Default: truewriteCoalescingMaxBatch?number. Maximum messages per batch before forcing flush. Default: 100writeCoalescingMaxDelayMs?number. Maximum delay in milliseconds before flushing. Lower values reduce latency. Default: 5writeCoalescingMaxBytes?number. Maximum batch size in bytes before flushing. Default: 65536 (64KB)
Rate Limiting Options
Protect against connection floods and DDoS attacks.
Rate LimitingParameters
rateLimitingEnabled?boolean. Enable connection rate limiting. Default: truemaxConnectionsPerSecond?number. Maximum new connections accepted per second. Default: 100maxPendingConnections?number. Maximum pending connection handshakes. Default: 1000
TLS Configuration
Enable TLS/SSL encryption for secure client connections (WSS) and cluster communication.
interface TLSConfigParameters
enabledboolean. Enable TLS for client-facing server (HTTPS + WSS). Default: falsecertPathstring. Path to the certificate file (PEM format). Supports chain certificates.keyPathstring. Path to the private key file (PEM format).caCertPath?string. Path to CA certificate for client certificate verification. Required for mTLS.minVersion?'TLSv1.2' | 'TLSv1.3'. Minimum TLS version. Default: 'TLSv1.2'ciphers?string. List of allowed cipher suites. Uses Node.js defaults if not specified.passphrase?string. Passphrase for encrypted private key.
interface ClusterTLSConfig extends TLSConfigParameters
requireClientCert?boolean. Require client certificate for mTLS (mutual TLS). Default: falserejectUnauthorized?boolean. Verify peer certificates. Can be disabled for self-signed certs in development. Default: true
Production Warning
When running in production without TLS enabled, the server will log a warning. Always enable TLS in production environments to protect client data in transit.Methods
constructor(config)
Creates a new server instance but does not start listening immediately.
ready()
Returns a Promise that resolves when the server is fully started and bound to the port.
const server = new ServerCoordinator(config);
await server.ready();
console.log(`Server running on port ${server.port}`); shutdown()
Gracefully shuts down the server, closing all client connections, stopping the cluster, and closing storage.
POST /sync Endpoint
Stateless HTTP sync endpoint for serverless environments. Accepts batched operations, returns deltas and query results in a single request-response cycle.
URL:
POST /syncAuthentication:
Authorization: Bearer <token> (required)
Content Types:
application/x-msgpack (default), application/json (fallback)Response Format:Matches request content type
Request Schema (HttpSyncRequest)
interface HttpSyncRequestParameters
clientIdstring. Client identifier. Required.clientHlcTimestamp. Client's current Hybrid Logical Clock as an object: { millis: number, counter: number, nodeId: string }. Required.operations?ClientOp[]. Batch of operations to push to the server. Each operation contains mapName, key, and record with value and timestamp.syncMaps?SyncMapEntry[]. Maps to pull deltas for. Each entry contains mapName (string) and lastSyncTimestamp (Timestamp) indicating the last known server state for that map.queries?HttpQueryRequest[]. One-shot queries to execute. Each query contains queryId (string), mapName (string), filter (object), and optional limit (number) and offset (number).searches?HttpSearchRequest[]. One-shot search requests to execute.
Response Schema (HttpSyncResponse)
interface HttpSyncResponseParameters
serverHlcTimestamp. Server's current HLC timestamp as an object: { millis: number, counter: number, nodeId: string }.ack?{ lastId: string, results?: AckResult[] }. Acknowledgment of processed operations. lastId is the ID of the last processed operation. results contains per-operation success/failure details with achievedLevel.deltas?MapDelta[]. Delta records for requested maps. Each MapDelta contains mapName (string), records (DeltaRecord[] with key, record: LWWRecord, eventType: 'PUT' | 'REMOVE'), and serverSyncTimestamp (Timestamp).queryResults?HttpQueryResult[]. Results for one-shot queries, matching the queryId from the request.searchResults?HttpSearchResult[]. Results for one-shot search requests.errors?HttpSyncError[]. Errors for individual operations. Each error contains code (number), message (string), and context (string, optional) identifying the failed operation.
HTTP Status Codes
| Status | Meaning |
|---|---|
| 200 | Success. Response body contains HttpSyncResponse. |
| 400 | Invalid request body. Zod schema validation failure. |
| 401 | Missing or invalid Authorization header. JWT verification failed. |
| 403 | Permission denied for specific operations. Individual errors appear in the response errors array. |
| 500 | Internal server error. |
Example Request
// POST /sync
// Content-Type: application/json
// Authorization: Bearer <your-jwt-token>
{
"clientId": "client-1",
"clientHlc": {
"millis": 1706000000000,
"counter": 0,
"nodeId": "client-1"
},
"operations": [
{
"mapName": "todos",
"key": "t1",
"record": {
"value": { "text": "Buy milk" },
"timestamp": {
"millis": 1706000000000,
"counter": 1,
"nodeId": "client-1"
}
}
}
],
"syncMaps": [
{
"mapName": "todos",
"lastSyncTimestamp": {
"millis": 1705999000000,
"counter": 0,
"nodeId": ""
}
}
]
} The example above uses JSON for readability. In production, the default wire format is
application/x-msgpack (msgpackr binary) for smaller payloads and faster serialization. Set Content-Type: application/json to use JSON instead.Example Response
// 200 OK
// Content-Type: application/json
{
"serverHlc": {
"millis": 1706000001000,
"counter": 1,
"nodeId": "server-1"
},
"ack": {
"lastId": "http-op-0",
"results": [
{
"opId": "http-op-0",
"success": true,
"achievedLevel": "MEMORY"
}
]
},
"deltas": [
{
"mapName": "todos",
"records": [
{
"key": "t2",
"record": {
"value": { "text": "Walk the dog" },
"timestamp": {
"millis": 1706000000500,
"counter": 0,
"nodeId": "client-2"
}
},
"eventType": "PUT"
}
],
"serverSyncTimestamp": {
"millis": 1706000001000,
"counter": 2,
"nodeId": "server-1"
}
}
],
"queryResults": [],
"searchResults": [],
"errors": []
}