惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
Google DeepMind News
Google DeepMind News
博客园 - 司徒正美
Y
Y Combinator Blog
F
Fortinet All Blogs
云风的 BLOG
云风的 BLOG
T
Tailwind CSS Blog
G
Google Developers Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
罗磊的独立博客
D
DataBreaches.Net
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
N
Netflix TechBlog - Medium
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
P
Proofpoint News Feed
Jina AI
Jina AI
B
Blog RSS Feed
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Understanding Apache Kafka: A Beginner's Guide to Real-ti...
Ng'ang'a Njo · 2026-05-19 · via DEV Community

Apache Kafka is a technology that is mainly used to build high-performance, real-time data pipelines and streaming applications. It handles vast quantities of data and this article aims to demystify Kafka for beginners. We will explain its core concepts and show its practical application through a real-time weather data processing example.

What is Apache Kafka?

Apache Kafka is an event streaming platform that is distributed, scalable, and fault-tolerant. Think of it as a highly efficient, persistent message queue that allows different applications to communicate by sending and receiving data streams. Kafka facilitates a publish-subscribe model where data producers send messages to a central system, and data consumers can read these messages independently.

Key Components of Apache Kafka

To understand how Kafka works, it's essential to grasp its fundamental components:

1. Producers
Producers are client applications that publish (write) data records (messages) to Kafka topics. They are responsible for creating new data and sending it to the Kafka cluster. For instance, in our weather data example, the Python script fetching weather information from an API acts as a producer.

2. Consumers
Consumers are client applications that subscribe to (read) data records from Kafka topics. They process the data streams published by producers.

3. Brokers
Brokers are the core servers that form the Kafka cluster. Each broker is a Kafka server that stores data, handles requests from producers and consumers, and replicates data for fault tolerance.

4. Topics and Partitions
Topics are categories or feeds to which records are published. They are logical channels for organizing data streams. For example, open_weather_data would be a topic for all weather-related messages. Topics are further divided into partitions, which are ordered, immutable sequences of records.

5. Zookeeper (or Kraft in newer versions)
Historically, Kafka relied on Apache ZooKeeper for managing the cluster's metadata. In newer versions of Kafka, Kraft has been introduced to remove the dependency on ZooKeeper, simplifying the architecture.

Building a Real-time Weather Data Processing Pipeline with Kafka

Let's illustrate these concepts with a practical example: a real-time weather data processing pipeline using the provided Python code. This pipeline demonstrates how producers fetch data, publish it to Kafka, and consumers then process it.

Producer Code Explanation

import requests
import json
from kafka import KafkaProducer
import time
from dotenv import load_dotenv
import os

load_dotenv()

api_key = os.getenv("API_KEY")

def get_weather_data():

    cities = ["Nairobi", "Mombasa", "Kisumu", "Eldoret", "Nakuru"]

    city_list = []

    for city in cities:

        url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"

        data = requests.get(url)

        raw_data = data.json()

        city_list.append(
            {
                "city": city,
                "temperature": raw_data["main"]["temp"],
                "humidity": raw_data["main"]["humidity"],
                "description": raw_data["weather"][0]["description"],
                "last_update": raw_data["dt"]
            }
        )

    return city_list

producer = KafkaProducer(
    bootstrap_servers='localhost:9092',
    value_serializer = lambda p:  json.dumps(p).encode('utf-8')
                            )


while True:
    weather_data = get_weather_data()
    topic = 'open_weather_data'
    producer.send(topic, value=weather_data)
    print(f"Producer: {weather_data}")
    time.sleep(5)

Enter fullscreen mode Exit fullscreen mode

  • The script fetches current weather data for a list of Kenyan cities from the OpenWeatherMap API.

  • It then extracts relevant weather details (city, temperature, humidity, description, last update timestamp) and returns them as a list of dictionaries.

  • We then specify the address of the brokers (localhost:9092) that the Producer will connect to.

  • value_serializer : Defines how the data sent to Kafka should be serialized. In our case, it converts the Python dictionary containing the weather data to json and then encodes it to utf-8, which is the format Kafka expects.

  • The while loop ensures we run the above steps continuously.

  • We then define a topic as, 'open_weather_data' and use producer.send(topic, value=weather_data) to publish the fetched weather data to the topic defined.

  • In our code, we've defined a pause of 5 seconds before fetching the next batch but this can be adjusted accordingly.

Consumer Code Explanation

from kafka import KafkaConsumer
import json

consumer = KafkaConsumer(
    'open_weather_data',
    bootstrap_servers='localhost:9092',
    value_deserializer = lambda m: json.loads(m.decode('utf-8')),
    auto_offset_reset='earliest'
)

for message in consumer:
    print(f"Consumer: {message.value}")

Enter fullscreen mode Exit fullscreen mode

  • 'open_weather_data' specifies the topic from which the consumer will read messages.

  • bootstrap_servers = 'localhost:9092' is the same as for the producer, pointing to the Kafka broker(s).

  • value_deserializer = lambda m: json.loads(m.decode('utf-8')) defines how the received data (value) from Kafka should be deserialized. It decodes the UTF-8 bytes back into a JSON string and then parses it into a Python dictionary.

  • auto_offset_reset = 'earliest' : 'earliest' means the consumer will start reading from the beginning of the topic (the earliest available offset). Other options include 'latest' (start from the most recent messages) or 'none' (throw an error if no valid offset is found).

Conclusion

Apache Kafka provides a robust and scalable solution for handling real-time data streams. By understanding its core components—producers, consumers, brokers, topics, and partitions—and seeing how they interact in a practical example like our weather data pipeline, you can begin to appreciate its power. This setup allows for efficient, decoupled communication between different parts of an application, enabling real-time data processing and analytics that are vital in today's fast-paced digital world.