Load testing a self-hosted KoboToolbox, Part 1: when every enumerator syncs at once
Executive Summary
Self-hosted KoboToolbox deployments often fail under load not because of CPU saturation, but due to database connection pool exhaustion and asynchronous task queue bottlenecks. During a controlled load test simulating a field deployment scenario, we observed that a single KoboToolbox pod handling 26 concurrent synchronization requests per second experienced a 17% failure rate in form submission and media upload endpoints. This latency spike was not caused by the web server itself, but by the underlying PostgreSQL connection limits and Celery worker backlog.
Conversely, a horizontally scaled deployment with Kubernetes Horizontal Pod Autoscaler (HPA) based on custom metrics (specifically Celery queue depth and PostgreSQL active connections) maintained a 0% failure rate. This article details the infrastructure topology, the specific Docker Compose configuration used for the baseline test, and the operational pitfalls encountered when scaling a monolithic-style self-hosted stack. The findings emphasize that for sovereign data ownership in high-throughput field data collection, vertical scaling of the database is a hard limit; horizontal scaling of the application layer is mandatory.
Implementation
The test environment was constructed using a local Kubernetes cluster (k3s) to simulate a production-like network topology, though the initial baseline was a Docker Compose setup for rapid iteration. The core components included:
- KoboToolbox (kobocat & django): The application layer.
- PostgreSQL 15: The primary database.
- Redis: Used for both caching and the Celery message broker.
- Celery Workers: Handling asynchronous tasks like form parsing and media processing.
- Nginx Ingress Controller: Managing traffic routing.
Docker Compose Baseline Configuration
The baseline test utilized a single pod configuration. The critical constraint was the POSTGRES_MAX_CONNECTIONS environment variable, which was left at the default 100, and the Celery concurrency set to 4.
# docker-compose.yml excerpt for KoboToolbox Baseline
version: '3.8'
services:
postgres:
image: postgres:15
environment:
POSTGRES_USER: kobo
POSTGRES_PASSWORD: secret
POSTGRES_DB: kobocat
POSTGRES_MAX_CONNECTIONS: 100 # Critical bottleneck
volumes:
- pg_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru
kobocat:
image: kobotoolbox/kobocat:latest
environment:
- DB_HOST=postgres
- DB_NAME=kobocat
- DB_USER=kobo
- DB_PASS=secret
- REDIS_HOST=redis
- CELERY_BROKER_URL=redis://redis:6379/0
- CELERY_RESULT_BACKEND=redis://redis:6379/1
depends_on:
- postgres
- redis
celery:
image: kobotoolbox/kobocat:latest
command: celery -A kobocat worker --loglevel=info --concurrency=4
environment:
- DB_HOST=postgres
- DB_NAME=kobocat
- DB_USER=kobo
- DB_PASS=secret
- REDIS_HOST=redis
- CELERY_BROKER_URL=redis://redis:6379/0
depends_on:
- postgres
- redis
volumes:
pg_data:
Load Testing Methodology
We used k6 to simulate 50 enumerators syncing simultaneously. The script targeted the /api/v1/assets/ and /api/v1/submissions/ endpoints. The load profile was a linear ramp-up to 26 requests per second, sustained for 5 minutes, followed by a sharp spike to 50 requests per second for 30 seconds.
// k6/load_test.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 26 }, // Ramp up to 26 rps
{ duration: '2m', target: 26 }, // Stay at 26 rps
{ duration: '30s', target: 50 }, // Spike to 50 rps
{ duration: '1m', target: 50 }, // Stay at 50 rps
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
http_req_failed: ['rate<0.01'], // 1% failure rate threshold
},
};
export default function () {
const res = http.post('http://localhost/api/v1/submissions/', JSON.stringify({
formhub_uuid: 'test-uuid',
uuid: 'test-uuid-' + Date.now(),
device_id: 'device-' + Math.random(),
start: new Date().toISOString(),
end: new Date().toISOString(),
today: new Date().toISOString(),
_id: 1,
_version: 'v1',
$Xform_id_string: 'test_form',
$status: 'submitted via web',
$reviewer: 'auto',
field1: 'data'
}), {
headers: { 'Content-Type': 'application/json' }
});
check(res, {
'status is 201': (r) => r.status === 201,
});
sleep(1);
}
ShVaSa Intuition
The failure mode observed in the single-pod deployment was not a CPU bottleneck but a connection starved state. PostgreSQL’s default max_connections of 100 is insufficient for a high-throughput application server combined with Celery workers. Each incoming HTTP request from KoboToolbox opens a database connection. When 26 requests arrive simultaneously, plus background Celery tasks, the connection pool saturates. New connections are queued or rejected, leading to the 17% error rate.
The intuition behind the successful autoscaled deployment lies in decoupling the request rate from the processing rate. By introducing an HPA that scales Celery workers based on Redis queue depth, we ensured that the application layer could accept requests (which are fast) while the background workers processed them (which are slow). The Nginx ingress layer buffered the initial burst, preventing the application from being overwhelmed by simultaneous TCP handshakes.
Infrastructure Topology
The following Mermaid diagram illustrates the data flow during the load test, highlighting the bottleneck point in the baseline and the mitigation in the scaled architecture.
graph TD
subgraph Client Layer [Enumerators]
A[Enumerator 1] -->|HTTPS| E[Load Balancer]
B[Enumerator 2] -->|HTTPS| E
C[Enumerator N] -->|HTTPS| E
end
subgraph Ingress Layer [Nginx Ingress]
E[Load Balancer] -->|Route| F[Ingress Controller]
end
subgraph Application Layer [Kubernetes Pods]
F -->|HTTP| G[KoboToolbox Pod 1]
F -->|HTTP| H[KoboToolbox Pod 2]
F -->|HTTP| I[KoboToolbox Pod N]
end
subgraph Async Layer [Celery Workers]
G -->|Publish Task| J[Redis Broker]
H -->|Publish Task| J
I -->|Publish Task| J
J -->|Consume Task| K[Celery Worker 1]
J -->|Consume Task| L[Celery Worker 2]
J -->|Consume Task| M[Celery Worker N]
end
subgraph Data Layer [PostgreSQL]
G -->|Query| N[(PostgreSQL)]
H -->|Query| N
I -->|Query| N
K -->|Update| N
L -->|Update| N
M -->|Update| N
end
style N fill:#f9f,stroke:#333,stroke-width:4px
style J fill:#ff9,stroke:#333,stroke-width:2px
Operational Pitfalls and Security
- Database Connection Limits: Always set
POSTGRES_MAX_CONNECTIONShigher than the sum of all application pods and worker concurrency. Usepgbounceras a connection pooler in front of PostgreSQL for production. - Redis Memory Management: In the baseline, Redis OOM (Out of Memory) errors occurred due to unbounded task queues. Configure
maxmemoryand an eviction policy (allkeys-lru) to prevent Redis from crashing under load. - Backup Strategy: For self-hosted KoboToolbox, regular backups of the PostgreSQL volume and the media storage (S3-compatible or local volume) are critical. Use
pg_dumpfor logical backups andrsyncorresticfor media files. - Security Hardening: Expose KoboToolbox only via HTTPS. Use a reverse proxy (Nginx/Traefik) with TLS termination. Ensure that the API keys and database credentials are stored in Kubernetes Secrets or a vault, not in environment variables in plain text.
This test demonstrates that self-hosting KoboToolbox requires careful attention to database connection management and asynchronous task processing. A single pod is insufficient for realistic field loads; horizontal scaling with proper metrics-driven autoscaling is essential for reliability.
Grounding & Source Attribution
- Original Topic: Load testing a self-hosted KoboToolbox, Part 1: when every enumerator syncs at once
- Primary Author / Dispatcher: Stephen Oduor via Medium Self-Hosting
- Curated and Synthesized by: ShVaSa Lab (Sharath Japa)
- Preserved Canonical URL: https://shvasa.us/posts/load-testing-a-self-hosted-kobotoolbox-part-1-when-every-enumerator-syncs-at-once