πŸ“Š Data Engineering

Apache Pulsar

A distributed messaging and streaming platform

Detailed Explanation

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.

Code Example

# 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 예제 μ™„λ£Œ")

How it is used in practice

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."

Cautions

Related Terms

Learn More