NATS JetStream vs Apache Kafka vs Apache Pulsar: Latency SLAs, Throughput & Multi-Tenancy
Vikram Sengupta
Engineering Team
Index(17 sections)
NATS JetStream vs Apache Kafka vs Apache Pulsar: Latency SLAs, Throughput & Multi-Tenancy
Executive Brief
A messaging platform does not have one latency number. Its observed latency depends on the producer acknowledgment policy, replication path, storage medium, batch policy, payload distribution, partition skew, consumer state, and failure conditions.
This distinction matters when teams compare NATS Core latency with durable Kafka writes or compare Pulsar broker throughput without accounting for BookKeeper traffic. These tests measure different contracts.
NATS JetStream, Kafka, and Pulsar can all retain events and support replay. Their failure domains differ:
- JetStream places messaging, stream ownership, and persistence within the NATS server topology. Stream and metadata replication use Raft groups.
- Kafka assigns ordered logs to partition leaders. Brokers replicate partition data while KRaft controllers manage cluster metadata.
- Pulsar separates broker ownership from durable BookKeeper storage. Metadata services coordinate topic ownership and cluster state.
The choice must follow the workload contract. A broker benchmark cannot establish an application SLA unless it reproduces the intended durability policy, backlog, tenant contention, and failure state.
Define the Evaluation Contract: Workload Shape, Delivery Guarantees, Durability, and Latency SLOs
Record these conditions before running a comparison:
- Latency boundary: producer call to durable acknowledgment, broker-to-consumer delivery, or complete business transaction.
- Workload shape: payload distribution, key skew, topic or subject cardinality, producer concurrency, and consumer fan-out.
- Durability: memory or file storage, replication policy, acknowledgment mode, and acceptable data-loss boundary.
- Delivery semantics: at-most-once, at-least-once, deduplication, or transactional processing.
- Recovery state: steady operation, replica loss, leader election, backlog replay, or storage throttling.
- Tenant model: shared credentials, logical namespace, resource quota, dedicated node pool, or dedicated cluster.
Measure p50 for the normal path, p95 for routine contention, and p99 or p99.9 for tail behavior. The higher percentiles usually expose disk queueing, garbage collection, page faults, elections, batch timers, and cross-tenant interference.
The primary semantic references are the JetStream model, Kafka design documentation, and Pulsar architecture overview.
Architecture Reference Topology (PlantUML)
The following topology shows equivalent durable publish paths. Dashed return paths represent acknowledgments after the configured commit condition. They do not imply equivalent persistence guarantees.
Core Engineering Mechanics
Compare the Architectural Primitives: JetStream Streams, Kafka Partitions, and Pulsar Managed Ledgers
JetStream maps subjects into streams. File-backed streams use block-oriented storage and indexes; memory-backed streams retain state in process memory. Each replicated stream has a Raft group, while a separate metadata group manages placement and cluster state. This model keeps the routing and storage path compact, but CPU, network, and storage pressure can meet within the same server process. See the JetStream clustering specification.
A stream can contain many subjects, but its replication leader remains a serialization and placement boundary. One hot stream can therefore saturate a server even when other servers have spare capacity.
Kafka stores each partition as an ordered sequence of log segments with offset and time indexes. Producers write through the partition leader. Followers copy that log, and consumers fetch by offset. Kafka relies heavily on sequential I/O and the operating-system page cache rather than retaining all payload data in the Java heap.
The partition defines ordering, producer parallelism, replica placement, and consumer-group concurrency. Adding partitions increases concurrency but can change key-to-partition mapping and operational load. Partition count is therefore a data-model decision, not only a capacity control.
Pulsar represents a topic through a managed ledger composed of BookKeeper ledgers. Brokers own topics and handle protocol operations, while bookies persist entries through journal and ledger storage paths. This separation lets teams scale serving and storage pools independently. It also adds broker-to-bookie network traffic and more distinct failure domains. BookKeeper describes its quorum and storage model in the official architecture documentation.
Trace the Latency-Critical Path: Acknowledgments, Replication, Persistence, Batching, and Backpressure
A JetStream producer receives a PubAck after the target stream accepts the publication under its configured replication policy. NATS Core publish latency is not a valid substitute because Core NATS does not provide the same retained-stream contract.
Kafka producer latency depends on acks, in-sync replica state, batch formation, compression, and broker load. An acks=all response means the current in-sync replica policy accepted the record. It does not automatically mean that every replica forced that record to physical media. Kafka’s page-cache and flush behavior must remain part of the durability review. The relevant controls are documented in the Kafka producer configuration reference.
Pulsar brokers acknowledge a durable send after the managed-ledger write satisfies the configured BookKeeper quorum. The path crosses the broker and storage tiers. A healthy broker with congested bookies still produces poor tail latency.
Batching amortizes protocol, checksum, compression, and system-call costs. It also introduces a wait boundary and makes latency sensitive to traffic rate. Test sparse traffic as well as saturated traffic.
Backpressure must be explicit:
- JetStream consumers need bounded pending acknowledgments and deliberate pull or flow-control behavior.
- Kafka producers need bounded buffers and delivery timeouts; consumers need controlled fetch sizes and processing concurrency.
- Pulsar producers and consumers need bounded pending messages, receiver queues, and permits.
Unbounded application queues can report low broker latency while moving the actual delay into process memory.
Engineer for Sustainable Throughput: Parallelism, Data Distribution, Hotspots, Storage, and Network Constraints
Throughput depends on bytes moved, not only message count. Record both publish calls and payload bytes. A batch containing many records is one protocol request but many messages.
JetStream scales through stream placement, subject design, replicas, and server resources. Kafka scales through partitions and leaders distributed across brokers. Pulsar scales through partitioned topics, namespace bundles, broker ownership, and BookKeeper placement.
For each platform, test:
- A uniform key distribution and the expected worst-case hot key.
- Normal consumers and consumers rebuilding from retention.
- Compression CPU against network and storage savings.
- Replica recovery while foreground traffic continues.
- A tenant producing excessive traffic beside an SLA-sensitive tenant.
The sustainable limit is the point before queue depth and p99 latency continue to rise. A short peak test cannot identify that boundary.
Design Multi-Tenant Boundaries: NATS Accounts, Kafka Quotas and ACLs, and Pulsar Tenants and Namespaces
NATS accounts create separate subject namespaces and authorization domains. Imports and exports provide controlled cross-account communication. JetStream limits can constrain account storage and resource use. Accounts are a strong logical boundary, but shared servers still expose tenants to common CPU, memory, network, and volume pressure. See NATS account security.
Kafka uses principals, ACLs, topics, client identifiers, and quotas. These controls govern authorization and traffic rates, but a shared broker still has common thread pools, page cache, disks, and partition-management work. A dedicated cluster remains the clearest hard boundary for tenants with separate failure or compliance domains. Kafka documents both ACL authorization and quota behavior.
Pulsar exposes tenants and namespaces as first-class policy scopes. Administrators can attach authentication, authorization, retention, backlog, replication, and rate policies to these scopes. Broker and BookKeeper capacity still remains shared unless placement or infrastructure policies separate it. See Pulsar multi-tenancy.
Do not treat namespace authorization as performance isolation. Validate quota enforcement during disk saturation, backlog replay, and broker or bookie loss.
Evaluate Reliability and Recovery: Retention, Replay, Deduplication, Failover, and Disaster-Recovery Trade-offs
JetStream supports limit-based, interest-based, and work-queue retention. Message identifiers can suppress duplicate publications within the configured deduplication window. Consumers still need idempotent side effects because a process can fail after applying an event but before acknowledging it.
Kafka supports time- or size-based retention and log compaction. Idempotent producers and transactions can coordinate Kafka writes and consumed offsets. They do not make an external database update atomic. Use a transactional outbox or an idempotency ledger at that boundary.
Pulsar retains subscription backlogs and supports deduplication and transactions. Its geo-replication model can replicate namespaces across clusters, while Kafka commonly uses replication tooling between clusters and JetStream can use streams, mirrors, or sources across domains.
Cross-region replication is normally asynchronous. Define recovery-point and recovery-time objectives from a tested failover procedure rather than from feature availability.
Assess Production Operability: Capacity Planning, Observability, Upgrades, Security, and Platform Ownership
Capacity plans must reserve headroom for elections, replica repair, compaction, retention deletion, and consumer catch-up. Monitor acknowledgment latency, queue depth, replica health, storage latency, network saturation, consumer lag or acknowledgment backlog, and authentication failures.
JetStream has fewer subsystem classes, but server placement requires care because routing and storage share resources. Kafka requires partition lifecycle, broker storage, and controller discipline. Pulsar requires operational ownership across brokers, metadata services, and BookKeeper.
The platform team must also rehearse certificate rotation, credential revocation, rolling upgrades, storage replacement, and schema compatibility. A managed service transfers some infrastructure work, but it does not remove workload design or incident ownership.
Production Code Implementation
The relay below publishes a PostgreSQL transactional outbox into JetStream. It uses a bounded database connection pool, environment-defined timeouts, row locking, durable publish acknowledgment, and a stable message identifier. A crash after publication but before deletion can cause redelivery, so consumers must remain idempotent.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/nats-io/nats.go"
)
type config struct {
dbURL, natsURL, creds, subjectPrefix string
operationTimeout, connectTimeout time.Duration
pollInterval, reconnectWait time.Duration
connMaxLifetime time.Duration
maxOpen, maxIdle int
}
func required(key string) string {
value := os.Getenv(key)
if value == "" {
log.Fatalf("%s is required", key)
}
return value
}
func duration(key string) time.Duration {
value, err := time.ParseDuration(required(key))
if err != nil {
log.Fatalf("parse %s: %v", key, err)
}
return value
}
func integer(key string) int {
value, err := strconv.Atoi(required(key))
if err != nil {
log.Fatalf("parse %s: %v", key, err)
}
return value
}
func loadConfig() config {
return config{
dbURL: required("DATABASE_URL"),
natsURL: required("NATS_URL"),
creds: required("NATS_CREDS"),
subjectPrefix: required("NATS_SUBJECT_PREFIX"),
operationTimeout: duration("OPERATION_TIMEOUT"),
connectTimeout: duration("CONNECT_TIMEOUT"),
pollInterval: duration("POLL_INTERVAL"),
reconnectWait: duration("RECONNECT_WAIT"),
connMaxLifetime: duration("DB_CONN_MAX_LIFETIME"),
maxOpen: integer("DB_MAX_OPEN"),
maxIdle: integer("DB_MAX_IDLE"),
}
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
cfg := loadConfig()
ctx, stop := signal.NotifyContext(
context.Background(), os.Interrupt, syscall.SIGTERM,
)
defer stop()
db, err := sql.Open("pgx", cfg.dbURL)
if err != nil {
return fmt.Errorf("open database: %w", err)
}
defer db.Close()
db.SetMaxOpenConns(cfg.maxOpen)
db.SetMaxIdleConns(cfg.maxIdle)
db.SetConnMaxLifetime(cfg.connMaxLifetime)
pingCtx, cancel := context.WithTimeout(ctx, cfg.connectTimeout)
err = db.PingContext(pingCtx)
cancel()
if err != nil {
return fmt.Errorf("ping database: %w", err)
}
nc, err := nats.Connect(
cfg.natsURL,
nats.UserCredentials(cfg.creds),
nats.Timeout(cfg.connectTimeout),
nats.ReconnectWait(cfg.reconnectWait),
nats.Name("transactional-outbox-relay"),
)
if err != nil {
return fmt.Errorf("connect NATS: %w", err)
}
defer nc.Close()
js, err := nc.JetStream()
if err != nil {
return fmt.Errorf("open JetStream context: %w", err)
}
for ctx.Err() == nil {
sent, relayErr := relayOne(ctx, db, js, cfg)
if relayErr != nil {
log.Printf("outbox relay failed: %v", relayErr)
}
if sent && relayErr == nil {
continue
}
timer := time.NewTimer(cfg.pollInterval)
select {
case <-ctx.Done():
timer.Stop()
case <-timer.C:
}
}
if err := nc.Drain(); err != nil {
return fmt.Errorf("drain NATS connection: %w", err)
}
return nil
}
func relayOne(
parent context.Context,
db *sql.DB,
js nats.JetStreamContext,
cfg config,
) (bool, error) {
ctx, cancel := context.WithTimeout(parent, cfg.operationTimeout)
defer cancel()
tx, err := db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
return false, fmt.Errorf("begin outbox transaction: %w", err)
}
defer tx.Rollback()
var id, subject string
var payload []byte
err = tx.QueryRowContext(ctx, `
SELECT id, subject, payload
FROM event_outbox
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1`).Scan(&id, &subject, &payload)
if err == sql.ErrNoRows {
return false, tx.Commit()
}
if err != nil {
return false, fmt.Errorf("read outbox: %w", err)
}
if !strings.HasPrefix(subject, cfg.subjectPrefix+".") {
return false, fmt.Errorf("subject %q escapes configured prefix", subject)
}
msg := &nats.Msg{Subject: subject, Data: payload, Header: nats.Header{}}
msg.Header.Set(nats.MsgIdHdr, id)
if _, err = js.PublishMsg(msg, nats.Context(ctx)); err != nil {
return false, fmt.Errorf("publish outbox record %s: %w", id, err)
}
if _, err = tx.ExecContext(
ctx, `DELETE FROM event_outbox WHERE id = $1`, id,
); err != nil {
return false, fmt.Errorf("delete outbox record %s: %w", id, err)
}
if err = tx.Commit(); err != nil {
return false, fmt.Errorf("commit outbox record %s: %w", id, err)
}
return true, nil
}The same outbox boundary can target Kafka or Pulsar through a typed publisher interface. Preserve the stable event identifier and do not hold the transaction beyond a bounded publish operation.
Quantitative Benchmark Evaluation
Cross-project benchmark figures are not reported here because the official tools use different defaults and test environments. Publishing such values as a ranking would create false precision. Populate this acceptance ledger from the target topology.
| Platform | p50 publish acknowledgment | p95 | p99 | Sustained RPS | Memory footprint | Primary measurement source |
|---|---|---|---|---|---|---|
| NATS JetStream | Required from client-side PubAck histogram | Required | Required under contention | Record calls, messages, and bytes | Record server RSS, cache, and host page cache | NATS JetStream benchmarking |
| Apache Kafka | Required from producer completion histogram | Required | Required during replica events | Record requests, records, batches, and bytes | Record JVM memory, direct buffers, and host page cache | Kafka performance tools |
| Apache Pulsar | Required from producer send-receipt histogram | Required | Required during broker and bookie events | Record sends, messages, entries, and bytes | Record broker, bookie, cache, and metadata-service memory | Pulsar performance tooling |
Use the OpenMessaging Benchmark framework when a common driver helps, but inspect each adapter and configuration. A valid report must publish raw histograms, payload distributions, batching settings, durability policies, topology, storage type, software revisions, warm-up method, and fault timeline.
Run separate steady-state, saturation, recovery, and noisy-neighbor phases. Accept a platform only when its tail latency remains within the workload SLO at the required sustainable throughput.
Trade-Off & Decision Matrix
| Platform | Strong fit | Main throughput boundary | Multi-tenant boundary | Failure blast radius | Cost envelope | Disqualifier |
|---|---|---|---|---|---|---|
| NATS JetStream | Unified request, event, and durable-stream fabric with compact operations | Hot stream leaders, server storage, replication traffic | Account, subject permissions, stream limits | Shared server resources plus per-stream Raft state | Fewer subsystem classes; storage scales with NATS servers | Workload requires Kafka protocol compatibility or independently scaled storage tiers |
| Apache Kafka | Long-lived partitioned logs, ordered key streams, and broad connector support | Partition leaders, broker disks, network, page cache | Principal, ACL, topic, client quota | Partition and broker failures; shared cluster contention | Broker storage and partition operations dominate; managed services can transfer labor | Workload cannot tolerate partition planning or needs a native tenant hierarchy |
| Apache Pulsar | Large tenant and namespace estates with separate serving and storage concerns | Broker ownership, BookKeeper quorum path, network between tiers | Tenant, namespace, policy, placement controls | Broker, bookie, metadata, and shared-storage contention | More subsystem classes; broker and storage pools scale independently | Team cannot operate and diagnose the broker, metadata, and BookKeeper tiers |
Sources: NATS JetStream, Kafka design, and Pulsar architecture.
A dedicated cluster provides the smallest cross-tenant blast radius for all three systems. Logical tenancy reduces infrastructure count, but it does not remove shared CPU, storage, network, control-plane, or operator failure modes.
Production Deployment Manifest
This Kubernetes policy creates a default-deny broker namespace, permits tenant workloads to reach only the named TLS data-plane port, and allows internal platform communication. Native broker authorization remains mandatory.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: event-backbone-default-deny
namespace: event-platform
spec:
podSelector: {}
policyTypes:
- Ingress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-authorized-tenant-clients
namespace: event-platform
spec:
podSelector:
matchLabels:
event.kumasoft.in/plane: data
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
event.kumasoft.in/broker-access: authorized
podSelector:
matchExpressions:
- key: event.kumasoft.in/role
operator: In
values:
- publisher
- consumer
ports:
- name: broker-tls
protocol: TCP
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-event-platform-internal
namespace: event-platform
spec:
podSelector:
matchLabels:
app.kubernetes.io/part-of: event-backbone
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
app.kubernetes.io/part-of: event-backbone
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-observability-scrape
namespace: event-platform
spec:
podSelector:
matchLabels:
app.kubernetes.io/part-of: event-backbone
policyTypes:
- Ingress
ingress:
- from:
- namespaceSelector:
matchLabels:
event.kumasoft.in/role: observability
ports:
- name: metrics
protocol: TCPKubernetes documents selector and additive-policy behavior in the NetworkPolicy specification. Protect namespace labels with admission policy. NetworkPolicy controls network reachability; it does not replace NATS accounts, Kafka ACLs, or Pulsar tenant authorization.
Executive Directive & Next Steps
Make the Platform Decision: Fit Criteria, Disqualifiers, and a Workload-Representative Validation Plan
Use JetStream when the platform benefits from NATS subject routing, request-reply, and retained streams under one operating model. Validate hot-stream placement, file-store latency, account limits, and replica recovery.
Use Kafka when the partitioned log is the primary abstraction and the organization already owns partition design, consumer lag, broker storage, and connector operations. Validate key skew, partition reassignment, page-cache pressure, and quota behavior.
Use Pulsar when tenant and namespace policy, independent broker and storage scaling, or built-in geo-replication justify the additional subsystem boundaries. Validate bookie saturation, metadata availability, topic ownership changes, and cross-tier network contention.
Platform leaders should require the following evidence before approval:
- A written workload and durability contract.
- Reproducible p50, p95, p99, and SLA-tail histograms.
- Throughput results expressed in messages and bytes.
- Memory results that include process memory and page cache.
- Broker, storage, network-partition, and control-plane fault tests.
- Noisy-neighbor tests with enforced tenant quotas.
- Replay and disaster-recovery exercises from retained data.
- An upgrade, credential-rotation, and certificate-rotation runbook.
- Named ownership for capacity, schemas, incident response, and cost.
Select the system whose failure behavior and operating model match the business contract. Treat peak benchmark throughput as supporting evidence, never as the decision itself.
Related Topics
Share This Article
More Engineering Architecture Playbooks
Deep dives and blueprints from our senior engineering team
Alpine Linux Security Advisory: OpenSSH-server password authentication bypass
Organizations should treat the advisory as an identity-boundary incident until package inventory, SSH configuration, network exposure, and access records establish otherwise. The paper will translate verified Alpine guidance into a production-safe workflow covering exposure analysis, containment, upgrades, validation, threat hunting, and recovery.
vLLM KV Cache PagedAttention Memory Management on NVIDIA H100 GPU Clusters
This whitepaper explains how vLLM uses PagedAttention and block-based KV cache management to decouple request growth from contiguous GPU-memory allocation. It translates those mechanics into a production architecture for NVIDIA H100 clusters, covering scheduling, topology, capacity governance, observability, resilience, and safe multi-tenant operations without relying on unsupported benchmark claims.
Critical CVE Alert: CVE-2024-27834 - Apple Multiple Products Improper Authentication Vulnerability
CVE-2024-27834 should be handled as a trust-boundary issue rather than a routine endpoint update because improper authentication can undermine assumptions about who or what is permitted to access protected resources. The paper will translate vendor-confirmed facts into an operational response spanning asset discovery, risk-based containment, controlled patch deployment, post-update verification, and executive governance without speculating beyond published evidence.