Apache Kafka is the industry standard for high-throughput, fault-tolerant event streaming — used for microservices communication, real-time data pipelines, audit logs, and activity feeds. Running Kafka on a Hong Kong VPS gives your event-driven services a durable message bus in Asia-Pacific, with producers and consumers in mainland China connecting via CN2 GIA at 30–50ms — far better than routing to Confluent Cloud’s US-based clusters.
When to Use Kafka vs Redis Pub/Sub vs Celery
| Factor | Kafka | Redis Pub/Sub | Celery + Redis |
|---|---|---|---|
| Message persistence | Yes — configurable retention | No — fire and forget | Yes — until acknowledged |
| Message replay | Yes — seek to any offset | No | No |
| Throughput | Millions/sec | 100K–500K/sec | Thousands/sec |
| Consumer groups | Yes — multiple independent consumers | No | Yes (queues) |
| Best for | Event sourcing, audit logs, data pipelines | Simple pub/sub, live notifications | Background job processing |
Step 1: Install Kafka with KRaft Mode (No ZooKeeper)
<code">apt update && apt install -y default-jdk-headless wget
# Download Kafka 3.7
KAFKA_VERSION="3.7.0"
SCALA_VERSION="2.13"
wget https://downloads.apache.org/kafka/${KAFKA_VERSION}/kafka_${SCALA_VERSION}-${KAFKA_VERSION}.tgz
tar xzf kafka_${SCALA_VERSION}-${KAFKA_VERSION}.tgz -C /opt/
ln -s /opt/kafka_${SCALA_VERSION}-${KAFKA_VERSION} /opt/kafka
useradd -m -s /bin/bash kafka
chown -R kafka:kafka /opt/kafka
# Generate cluster UUID (KRaft mode — no ZooKeeper needed)
KAFKA_CLUSTER_ID=$(/opt/kafka/bin/kafka-storage.sh random-uuid)
echo "Cluster ID: $KAFKA_CLUSTER_ID"
Kafka Configuration
<code">cat > /opt/kafka/config/kraft/server.properties << EOF # KRaft mode — no ZooKeeper process.roles=broker,controller node.id=1 controller.quorum.voters=1@localhost:9093 # Listeners listeners=PLAINTEXT://127.0.0.1:9092,CONTROLLER://localhost:9093 advertised.listeners=PLAINTEXT://YOUR_VPS_IP:9092 listener.security.protocol.map=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT controller.listener.names=CONTROLLER inter.broker.listener.name=PLAINTEXT # Storage log.dirs=/opt/kafka/data # Retention (keep 7 days of events) log.retention.hours=168 log.retention.bytes=10737418240 # 10 GB per partition log.segment.bytes=1073741824 # 1 GB segments # Performance num.io.threads=8 num.network.threads=3 socket.send.buffer.bytes=102400 socket.receive.buffer.bytes=102400 socket.request.max.bytes=104857600 # Replication (single node — factor 1) default.replication.factor=1 min.insync.replicas=1 num.partitions=3 EOF # Format storage mkdir -p /opt/kafka/data /opt/kafka/bin/kafka-storage.sh format \ -t $KAFKA_CLUSTER_ID \ -c /opt/kafka/config/kraft/server.properties chown -R kafka:kafka /opt/kafka/data
Systemd Service
<code">cat > /etc/systemd/system/kafka.service << 'EOF' [Unit] Description=Apache Kafka After=network.target [Service] Type=simple User=kafka Environment="JAVA_HOME=/usr/lib/jvm/default-java" ExecStart=/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/kraft/server.properties ExecStop=/opt/kafka/bin/kafka-server-stop.sh Restart=always RestartSec=10 LimitNOFILE=100000 [Install] WantedBy=multi-user.target EOF systemctl enable --now kafka sleep 5 /opt/kafka/bin/kafka-topics.sh --list --bootstrap-server localhost:9092
Step 2: Create Topics
<code"># Create topics for your application /opt/kafka/bin/kafka-topics.sh --create \ --bootstrap-server localhost:9092 \ --topic orders \ --partitions 6 \ --replication-factor 1 \ --config retention.ms=604800000 # 7 days /opt/kafka/bin/kafka-topics.sh --create \ --bootstrap-server localhost:9092 \ --topic user-events \ --partitions 12 \ --replication-factor 1 /opt/kafka/bin/kafka-topics.sh --create \ --bootstrap-server localhost:9092 \ --topic notifications \ --partitions 3 \ --replication-factor 1 # List topics /opt/kafka/bin/kafka-topics.sh --list --bootstrap-server localhost:9092
Step 3: Produce and Consume Messages (Python)
<code"># pip install kafka-python-ng
from kafka import KafkaProducer, KafkaConsumer
import json
from datetime import datetime
# Producer
producer = KafkaProducer(
bootstrap_servers=['YOUR_VPS_IP:9092'],
value_serializer=lambda v: json.dumps(v).encode('utf-8'),
key_serializer=lambda k: k.encode('utf-8') if k else None,
acks='all', # Wait for all replicas to acknowledge
retries=3,
max_in_flight_requests_per_connection=1, # Preserve ordering
)
def publish_order_event(order: dict):
"""Publish order event — key ensures same order_id goes to same partition."""
producer.send(
topic='orders',
key=str(order['order_id']), # Partitioned by order_id
value={
'event_type': 'order.created',
'order_id': order['order_id'],
'user_id': order['user_id'],
'amount': order['amount'],
'currency': 'HKD',
'timestamp': datetime.utcnow().isoformat(),
}
)
producer.flush()
publish_order_event({'order_id': 'ORD-001', 'user_id': 42, 'amount': 299.00})
# Consumer — inventory service
consumer = KafkaConsumer(
'orders',
bootstrap_servers=['YOUR_VPS_IP:9092'],
group_id='inventory-service', # Consumer group — each group reads all messages
value_deserializer=lambda m: json.loads(m.decode('utf-8')),
auto_offset_reset='earliest', # Start from beginning if no committed offset
enable_auto_commit=False, # Manual commit after processing
)
for message in consumer:
event = message.value
if event['event_type'] == 'order.created':
# Process inventory update
update_inventory(event['order_id'])
consumer.commit() # Only commit after successful processing
Step 4: Multiple Consumer Groups
<code"># Each service has its own consumer group — they ALL receive every message # inventory-service: updates stock levels # notification-service: sends order confirmation emails # analytics-service: records metrics # fulfillment-service: triggers shipping # Run separate consumer instances: python inventory_consumer.py # group_id='inventory-service' python notification_consumer.py # group_id='notification-service' python analytics_consumer.py # group_id='analytics-service' # Each gets an independent cursor into the 'orders' topic # New consumer group joining later can replay all historical events
Step 5: Kafka with Node.js (KafkaJS)
<code"># npm install kafkajs
import { Kafka, logLevel } from 'kafkajs'
const kafka = new Kafka({
brokers: ['YOUR_VPS_IP:9092'],
logLevel: logLevel.ERROR,
})
// Producer
const producer = kafka.producer()
await producer.connect()
await producer.send({
topic: 'user-events',
messages: [
{
key: userId.toString(),
value: JSON.stringify({
event: 'page_viewed',
userId,
page: '/products/123',
timestamp: Date.now(),
}),
},
],
})
// Consumer
const consumer = kafka.consumer({ groupId: 'analytics-service' })
await consumer.connect()
await consumer.subscribe({ topic: 'user-events', fromBeginning: false })
await consumer.run({
eachMessage: async ({ message }) => {
const event = JSON.parse(message.value!.toString())
await trackEvent(event)
},
})
Step 6: Monitoring with Kafka UI
<code">docker run -d \
--name kafka-ui \
--restart unless-stopped \
-p 127.0.0.1:8090:8080 \
-e KAFKA_CLUSTERS_0_NAME=hk-vps \
-e KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS=host.docker.internal:9092 \
provectuslabs/kafka-ui:latest
# Expose via Nginx with IP restriction
cat >> /etc/nginx/sites-available/kafka << 'EOF'
server {
listen 443 ssl http2;
server_name kafka-ui.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/kafka-ui.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/kafka-ui.yourdomain.com/privkey.pem;
allow YOUR_OFFICE_IP;
deny all;
location / { proxy_pass http://127.0.0.1:8090; }
}
EOF
Resource Requirements on HK VPS
| Config | RAM | CPU | Disk (7-day retention) |
|---|---|---|---|
| Kafka broker (single node) | 1–2 GB JVM heap | Low at <10K msg/s | Depends on message volume |
| 10K messages/sec, 1 KB avg | 2 GB | 2 vCPU | ~60 GB/day |
| 1K messages/sec, 1 KB avg | 1 GB | 1 vCPU | ~6 GB/day |
| Kafka UI | 256 MB | Minimal | None |
Conclusion
Apache Kafka on a Hong Kong VPS brings durable, replayable event streaming to your Asia-Pacific architecture — microservices in mainland China connect at 30–50ms, multiple consumer groups process the same event stream independently, and Kafka’s retention policy enables replaying historical events to rebuild application state or onboard new services without data loss. KRaft mode (no ZooKeeper) simplifies single-node deployment significantly, making Kafka practical on a mid-range VPS plan.
Build event-driven systems: Browse Server.HK Hong Kong VPS plans — a 4–8 GB plan runs Kafka comfortably alongside your application services for most microservices workloads.