Apache Pulsar
A distributed messaging and streaming platform
A distributed messaging and streaming platform
Apache Pulsar is a cloud-native distributed messaging and streaming platform developed at Yahoo that provides message queuing and stream processing together in a single system. It is attracting attention as an alternative to Kafka, and provides enterprise-grade features such as multi-tenancy, geo-replication, and tiered storage out of the box.
Pulsar's core architecture separates the serving layer (Broker) from the storage layer (BookKeeper). The Broker handles requests from producers and consumers, and Apache BookKeeper stores messages persistently. Thanks to this separation, each layer can be scaled independently, allowing flexible response to compute-intensive or storage-intensive workloads.
Multi-tenancy is a distinguishing feature of Pulsar, allowing multiple teams or applications to be isolated and operated on a single cluster. Through the hierarchy of Tenant, Namespace, and Topic, resource quotas, security policies, and message retention policies can be controlled in fine detail.
Pulsar supports four subscription modes: Exclusive, Shared, Failover, and Key_Shared. In particular, in Key_Shared mode, messages with the same key are always delivered to the same consumer, so ordering is guaranteed while parallel processing is still possible. Pulsar Functions and Pulsar IO also provide serverless stream processing and connector capabilities.
# Apache Pulsar Producer/Consumer μμ (Python)
import pulsar
from pulsar.schema import *
import json
import time
# ============================================
# 1. κΈ°λ³Έ Producer/Consumer
# ============================================
# ν΄λΌμ΄μΈνΈ μμ±
client = pulsar.Client(
'pulsar://localhost:6650',
authentication=pulsar.AuthenticationToken('your-token'),
operation_timeout_seconds=30,
connection_timeout_seconds=30
)
# Producer μμ±
producer = client.create_producer(
'persistent://public/default/user-events',
producer_name='event-producer-1',
send_timeout_millis=30000,
batching_enabled=True,
batching_max_messages=1000,
batching_max_publish_delay_ms=10,
compression_type=pulsar.CompressionType.ZSTD
)
# λ©μμ§ μ μ‘
for i in range(100):
event = {
'event_id': f'evt_{i}',
'user_id': f'user_{i % 10}',
'event_type': 'click',
'timestamp': int(time.time() * 1000)
}
# λκΈ° μ μ‘
message_id = producer.send(
json.dumps(event).encode('utf-8'),
properties={'source': 'web', 'version': '1.0'},
partition_key=event['user_id'] # νν°μ
ν€λ‘ μμ 보μ₯
)
print(f"Sent message: {message_id}")
# λΉλκΈ° μ μ‘
def send_callback(result, msg_id):
if result == pulsar.Result.Ok:
print(f"Message sent: {msg_id}")
else:
print(f"Failed to send: {result}")
producer.send_async(
b'async message',
callback=send_callback
)
producer.flush() # λ°°μΉ λ©μμ§ μ¦μ μ μ‘
# ============================================
# 2. Consumer ꡬλ
λͺ¨λ
# ============================================
# Exclusive ꡬλ
(λ¨μΌ 컨μλ¨Έ)
exclusive_consumer = client.subscribe(
'persistent://public/default/user-events',
subscription_name='exclusive-sub',
consumer_type=pulsar.ConsumerType.Exclusive,
initial_position=pulsar.InitialPosition.Earliest
)
# Shared ꡬλ
(λ€μ€ 컨μλ¨Έ λΌμ΄λ λ‘λΉ)
shared_consumer = client.subscribe(
'persistent://public/default/user-events',
subscription_name='shared-sub',
consumer_type=pulsar.ConsumerType.Shared,
receiver_queue_size=1000
)
# Key_Shared ꡬλ
(ν€ κΈ°λ° μμ 보μ₯ + λ³λ ¬ μ²λ¦¬)
key_shared_consumer = client.subscribe(
'persistent://public/default/user-events',
subscription_name='key-shared-sub',
consumer_type=pulsar.ConsumerType.KeyShared,
key_shared_policy=pulsar.KeySharedPolicy(
pulsar.KeySharedMode.AutoSplit
)
)
# λ©μμ§ μμ λ° μ²λ¦¬
while True:
try:
msg = shared_consumer.receive(timeout_millis=5000)
data = json.loads(msg.data().decode('utf-8'))
print(f"Received: {data}")
print(f"Properties: {msg.properties()}")
print(f"Message ID: {msg.message_id()}")
print(f"Publish Time: {msg.publish_timestamp()}")
# μ²λ¦¬ μλ£ ν ACK
shared_consumer.acknowledge(msg)
except pulsar.Timeout:
print("No message received")
continue
except Exception as e:
# μ²λ¦¬ μ€ν¨ μ Negative ACK (μ¬μ μ‘)
shared_consumer.negative_acknowledge(msg)
print(f"Error: {e}")
# ============================================
# 3. Schema κΈ°λ° λ©μμ§
# ============================================
class UserEvent(Record):
event_id = String()
user_id = String()
event_type = String()
timestamp = Long()
metadata = Map(String(), String())
# Schema Producer
schema_producer = client.create_producer(
'persistent://public/default/schema-events',
schema=AvroSchema(UserEvent)
)
event = UserEvent(
event_id='evt_001',
user_id='user_1',
event_type='purchase',
timestamp=int(time.time() * 1000),
metadata={'product': 'laptop', 'price': '1200'}
)
schema_producer.send(event)
# Schema Consumer
schema_consumer = client.subscribe(
'persistent://public/default/schema-events',
subscription_name='schema-sub',
schema=AvroSchema(UserEvent)
)
msg = schema_consumer.receive()
user_event = msg.value()
print(f"Event: {user_event.event_type} by {user_event.user_id}")
# ============================================
# 4. Dead Letter Topic μ€μ
# ============================================
dlq_consumer = client.subscribe(
'persistent://public/default/user-events',
subscription_name='dlq-enabled-sub',
consumer_type=pulsar.ConsumerType.Shared,
dead_letter_policy=pulsar.ConsumerDeadLetterPolicy(
max_redeliver_count=3,
dead_letter_topic='persistent://public/default/user-events-dlq'
),
negative_ack_redelivery_delay_ms=1000
)
# ============================================
# 5. Reader (λΉκ΅¬λ
μ½κΈ°)
# ============================================
# νΉμ μμΉλΆν° μ½κΈ° (ꡬλ
μν μμ)
reader = client.create_reader(
'persistent://public/default/user-events',
start_message_id=pulsar.MessageId.earliest,
reader_name='analytics-reader'
)
while reader.has_message_available():
msg = reader.read_next(timeout_millis=1000)
print(f"Read: {msg.data()}")
# ============================================
# 6. Pulsar Admin API (ν ν½ κ΄λ¦¬)
# ============================================
from pulsar import admin
# Admin ν΄λΌμ΄μΈνΈ μμ±
admin_client = admin.PulsarAdmin(
admin_url='http://localhost:8080',
auth_token='your-token'
)
# ν
λνΈ μμ±
admin_client.tenants().create(
tenant='my-company',
admin_roles=['admin'],
allowed_clusters=['standalone']
)
# λ€μμ€νμ΄μ€ μμ±
admin_client.namespaces().create('my-company/analytics')
# λ€μμ€νμ΄μ€ μ μ±
μ€μ
admin_client.namespaces().set_retention(
'my-company/analytics',
retention_time_minutes=60 * 24 * 7, # 7μΌ
retention_size_mb=10 * 1024 # 10GB
)
# ν ν½ μμ± (νν°μ
)
admin_client.topics().create_partitioned_topic(
'persistent://my-company/analytics/events',
num_partitions=8
)
# ν ν½ ν΅κ³ μ‘°ν
stats = admin_client.topics().get_stats(
'persistent://my-company/analytics/events'
)
print(f"Messages in: {stats['msgInCounter']}")
print(f"Messages out: {stats['msgOutCounter']}")
print(f"Storage size: {stats['storageSize']}")
# ============================================
# 7. Geo-Replication μ€μ (CLI)
# ============================================
"""
# ν΄λ¬μ€ν° λ±λ‘
pulsar-admin clusters create cluster-us \\
--url http://us-broker:8080 \\
--broker-url pulsar://us-broker:6650
pulsar-admin clusters create cluster-eu \\
--url http://eu-broker:8080 \\
--broker-url pulsar://eu-broker:6650
# λ€μμ€νμ΄μ€μ 볡μ μ€μ
pulsar-admin namespaces set-clusters \\
my-company/analytics \\
--clusters cluster-us,cluster-eu
"""
# ============================================
# 8. Tiered Storage μ€μ (conf/broker.conf)
# ============================================
"""
# AWS S3 μ€νλ‘λ μ€μ
managedLedgerOffloadDriver=aws-s3
s3ManagedLedgerOffloadBucket=pulsar-offload-bucket
s3ManagedLedgerOffloadRegion=ap-northeast-2
s3ManagedLedgerOffloadServiceEndpoint=https://s3.ap-northeast-2.amazonaws.com
# μ€νλ‘λ μκ³κ° (100MB μ΄κ³Ό μ μ€νλ‘λ)
managedLedgerOffloadThresholdInBytes=104857600
# μμ μ§μ° μκ°
managedLedgerOffloadDeletionLagInMillis=14400000
"""
# μ 리
producer.close()
shared_consumer.close()
client.close()
print("Pulsar μμ μλ£")
Infrastructure Engineer: "Our Kafka cluster is currently shared by several teams, and resource isolation isn't working well. A traffic spike from one team is affecting the other teams."
Architect: "If we migrate to Pulsar, multi-tenancy lets us isolate each team. We can set rate limits and quotas per tenant, and we can also apply different retention policies per namespace."
Infrastructure Engineer: "Storage cost is a problem too. Can we move old data to S3?"
Architect: "Pulsar's Tiered Storage feature handles automatic offloading. Segments above a certain size are moved to S3, and they are automatically fetched and processed when queried."
Interviewer: "Please explain the architectural differences between Apache Pulsar and Kafka, and in which situations you would choose each."
Candidate: "The key difference is the separation of compute and storage. In Kafka, the broker handles both data storage and serving, whereas in Pulsar, the Broker handles only serving and BookKeeper handles only storage. Because of this, Pulsar can scale each layer independently, and recovery is faster when a broker fails. If you need multi-tenancy, Geo-replication, and Tiered Storage, Pulsar has the advantage, and for a team with a mature ecosystem and rich operational experience, Kafka is the stable choice."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free
Reviewer: "In the Consumer, you only call negative_acknowledge on processing failure, but without a DLQ configuration it could be retried infinitely."
Developer: "Do I need to configure a Dead Letter Topic?"
Reviewer: "Yes, if you set max_redeliver_count, messages are moved to the DLQ once that count is exceeded. You should also set negative_ack_redelivery_delay to put an interval between retries. If a transient error is retried immediately, it is likely to fail again."