Reading Mode
CH 14·Lesson 5
Phase 5 — Celery & Kafka — Checkpoint Answer Guide
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
advanced9 min read
Learning Objectives
- Celery Basics
- Celery Advanced
- Kafka Fundamentals
- Kafka with Python
- Kafka Advanced
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
Celery Basics
- Task definition & calling: A Celery task is a registered message-handling contract; delay is shorthand while apply_async exposes routing, ETA, expiry, and options. A strong answer also explains that the producer serializes task name, IDs, arguments, and headers. Worker and backend state may be absent or eventually updated; PENDING can mean unknown, not queued. The main warning is: Waiting synchronously on a task result inside a request defeats decoupling and can deadlock workflows.
- Brokers & result backends: The broker transports work; the result backend stores task metadata or return values. They solve different problems. A strong answer also explains that delivery guarantees follow broker acknowledgment and visibility rules. AsyncResult is a client view over backend state, not a durable business record. The main warning is: Do not use a result backend as the only system of record.
- Celery Beat (periodic tasks): Beat is a scheduler that publishes due tasks; workers still execute them. A strong answer also explains that only one active scheduler should own a schedule unless the scheduler itself coordinates leadership. Database schedulers turn rows into publish decisions. The main warning is: Multiple beat instances can duplicate work.
- Monitoring: Task monitoring combines worker events, broker depth, runtime, retries, failures, and business completion. A strong answer also explains that workers emit an event stream when enabled; exporters translate broker and process state into metrics. The main warning is: Event monitoring adds overhead and may be incomplete; reconcile with domain records.
- Complete Django integration: Django's Celery bootstrap creates one Celery application, loads Django settings, and exposes it early enough for shared-task decorators to bind to the correct app. A strong answer also explains that the module sets the Django settings environment, constructs
Celery, imports configuration from the chosen namespace, and discovers registered tasks. Importing it from the project package makes worker and web processes share configuration. The main warning is: Creating multiple app objects or importing models before Django setup causes missing tasks, circular imports, and inconsistent configuration.
Celery Advanced
- Canvas: chains, groups, chords: Celery Canvas composes immutable or mutable task signatures into sequential, parallel, and fan-in workflows. A strong answer also explains that chains pass results forward; groups schedule siblings; chords require backend support to observe all header completions before a callback. The main warning is: Large chords stress result backends and one failed header can block the callback.
- Priority queues & DLQ: Queue routing isolates workloads by latency, resource profile, or priority; dead-letter handling preserves terminal failures for diagnosis. A strong answer also explains that the broker's priority semantics and worker prefetch determine whether priority is actually observed. The main warning is: Priority cannot preempt work already reserved or executing.
- Error handling & retries: Retries repeat a failed operation after a controlled delay; idempotency makes repeated attempts produce one logical effect. A strong answer also explains that exponential backoff increases delay and jitter prevents synchronized retry storms. A stable operation key or database constraint deduplicates effects. The main warning is: Retrying validation errors or non-idempotent external writes can amplify damage.
- Bulk Canvas operations: Celery Canvas composes immutable or mutable task signatures into sequential, parallel, and fan-in workflows. A strong answer also explains that chains pass results forward; groups schedule siblings; chords require backend support to observe all header completions before a callback. The main warning is: Large chords stress result backends and one failed header can block the callback.
Kafka Fundamentals
- Core concepts: A Kafka topic is split into ordered partitions whose records have monotonically increasing offsets. Retention removes old segments; compaction retains the latest value per key. A strong answer also explains that each partition has a leader and replicas. The in-sync replica set tracks followers sufficiently caught up; KRaft stores cluster metadata in a Raft quorum. The main warning is: Offsets are only unique within a partition; compaction does not preserve every intermediate event.
- Producers: Producer settings balance latency, throughput, ordering, and durability. A strong answer also explains that records accumulate per partition, are compressed and sent in batches.
acks=allwaits for the configured replica condition; idempotence uses producer IDs and sequence numbers to suppress retry duplicates within Kafka. The main warning is:acks=allis not sufficient if replication or minimum ISR is misconfigured. - Consumers & consumer groups: A consumer group divides partitions so one member owns a partition at a time; committed offsets represent recoverable progress. A strong answer also explains that polling drives heartbeats and fetches. Rebalances revoke and reassign ownership. Commit-before-processing risks loss; commit-after-processing permits duplicates. The main warning is: Slow processing beyond poll limits causes rebalances and duplicate work.
- Event model & compression: Kafka records carry key, value, timestamp, headers, and metadata; events state facts while commands express requested intent. Batch compression trades CPU for network, broker storage, and page-cache efficiency. A strong answer also explains that compression is applied to producer batches: better batching improves ratio. Keys choose partitions, so skewed business identities create hot leaders regardless of total partition count. The main warning is: Random keys remove ordering; one celebrity/tenant key can cap throughput at one partition.
Kafka with Python
- confluent-kafka & kafka-python: Python clients expose Kafka's producer accumulator, consumer poll loop, and administrative APIs with different performance and async trade-offs. A strong answer also explains that confluent-kafka delegates protocol work to librdkafka background threads; callbacks are served when the application polls or flushes. The main warning is: Calling flush after every message destroys batching.
- Error handling & DLQ: Retry topics delay reprocessing without blocking the main partition; a dead-letter topic stores messages that exhausted policy. A strong answer also explains that consumers publish an envelope containing original topic/partition/offset, event identity, attempt count, and sanitized error, then commit according to the handoff design. The main warning is: A DLT without ownership, retention, and replay policy is only a data graveyard.
- Schema Registry & Avro: Schema Registry gives events a versioned contract; Avro encodes data compactly against that schema. A strong answer also explains that a wire header identifies the registered schema; readers resolve writer and reader schemas under compatibility rules. The main warning is: Changing meaning without changing a field name is still a breaking semantic change.
- Producer & consumer modes: Kafka client mode choices define serialization, delivery callbacks, partition assignment, commit ownership, transactional identity, and asynchronous polling behavior. A strong answer also explains that producers batch and deliver in the background while application polling serves callbacks; consumers either subscribe for group-managed assignment or explicitly assign partitions and then commit only according to the chosen processing guarantee. The main warning is: A JSON serializer is not a DRF serializer, and manual assignment does not participate in consumer-group rebalancing.
Kafka Advanced
- Exactly-once semantics: Processing guarantees describe where duplicates or loss can occur; Kafka transactions can atomically publish output records and consumed offsets within Kafka. A strong answer also explains that an idempotent transactional producer uses a transactional ID and epoch; consumers using read_committed hide aborted writes. The main warning is: EOS does not make an arbitrary HTTP call or database write exactly once.
- Security & monitoring: TLS protects transport, SASL authenticates clients, ACLs authorize operations, and telemetry reveals durability and latency risk. A strong answer also explains that brokers evaluate a principal's operation against resource patterns. JMX exporters expose controller, broker, replica, request, and group measurements. The main warning is: Encryption without hostname verification or authorization is incomplete.
- Kafka Connect: Kafka Connect runs standardized source and sink connectors with distributed configuration, offsets, tasks, and converters. A strong answer also explains that workers coordinate connectors and task assignments; source offsets track extraction progress and sink tasks consume Kafka partitions. The main warning is: A connector does not automatically solve source consistency, deletes, or sink idempotency.
- Kafka Streams vs Flink: Kafka Streams is an embedded JVM library tightly integrated with Kafka partitions and changelogged local state; Flink is an independent distributed engine with richer event-time, state, and multi-source processing. A strong answer also explains that streams tasks follow Kafka partition assignment and restore RocksDB state from changelogs. Flink operators checkpoint distributed state and use watermarks to decide event-time completeness; savepoints support controlled upgrades. The main warning is: Neither engine fixes bad keys, unbounded state, or undefined late-event policy.
- Alert rule reference: A consumer group divides partitions so one member owns a partition at a time; committed offsets represent recoverable progress. A strong answer also explains that polling drives heartbeats and fetches. Rebalances revoke and reassign ownership. Commit-before-processing risks loss; commit-after-processing permits duplicates. The main warning is: Slow processing beyond poll limits causes rebalances and duplicate work.
Professional standard
A complete response identifies the boundary, guarantee, state owner, lifecycle, failure, and proof. Award less credit to answers that name tools without explaining why their guarantees fit the requirement.
Mastery check
How well can you recall this?
Finished this lesson?