Polling's over. Real-time starts here.
Through 21 chapters, you've been the one starting conversations with APIs. Need Spotify data? Make a request. Want GitHub issues? Query the endpoint. This pull model works perfectly when you control the timing. But some integrations demand the opposite pattern. Payment processors need to tell you instantly when charges succeed. GitHub wants to notify you the moment someone opens a pull request. Stripe can't wait 30 seconds for you to poll and ask if anything happened.
Webhooks flip the entire model. Instead of you calling APIs repeatedly, APIs call you when events occur. The provider sends an HTTP POST to your endpoint with event details. No polling loops, no wasted requests, no artificial delays. The moment something interesting happens, you know about it.
This chapter teaches you to build webhook receivers that are secure, reliable, and production-ready. You'll build a complete GitHub Activity Notifier that sends real-time Slack alerts for repository events. By the end, APIs won't just respond to you. They'll talk back to you.
A webhook is an HTTP callback. When something happens in a service (GitHub, Stripe, Slack), that service makes an HTTP POST request to a URL you control. The POST includes a JSON payload describing what happened. Your application receives the request, processes the event, and returns a response. That's it.
The name "webhook" suggests hooking into events, but technically it's just the provider POSTing to your endpoint. GitHub doesn't know or care what your endpoint does with the data. It just sends the POST and moves on. The pattern works because HTTP is universal and POST requests are simple.
What You'll Build: GitHub Activity Notifier
The GitHub Activity Notifier monitors your repositories and sends instant Slack notifications for important events. Four core features demonstrate different webhook integration patterns:
Real-Time Issue Alerts
Get notified instantly when issues open in your repositories. Your webhook receiver captures the event, extracts issue details (title, number, author), and posts a formatted Slack message within seconds. No polling delays, no missed notifications. The system proves webhooks eliminate the gap between event and awareness.
Pull Request Tracking
Monitor the entire PR lifecycle: opens, merges, closures, review requests. Each state change triggers a targeted notification. When teammates merge code at 2am, you see it immediately. When critical reviews await, Slack alerts you. This feature shows how webhook event types map to business logic and demonstrates conditional notification routing based on event metadata.
Repository Activity Feed
Track organic repository growth through stars, forks, and watchers. When developers star your projects, you celebrate wins in real-time. The system aggregates low-frequency events that would be wasteful to poll but valuable to know about. This proves webhooks handle both high-volume critical events and sparse vanity metrics efficiently.
Custom Event Routing and Filtering
Not every webhook deserves attention. Your system filters noise, routes different event types to different Slack channels, and marks uninteresting events as skipped rather than processed. This demonstrates production-grade webhook handling where intelligent filtering prevents alert fatigue and keeps notification channels focused on what matters.
These aren't toy features. Real-time issue alerts prove you understand event-driven architectures. Pull request tracking demonstrates you can parse complex JSON payloads and route events conditionally. Repository activity feeds show you handle both critical and informational events. Custom filtering proves you build systems that stay useful at scale, not alert factories that train teams to ignore notifications.
More importantly, webhooks are infrastructure-level skills. Payment processors (Stripe, PayPal), communication platforms (Slack, Discord, Twilio), version control (GitHub, GitLab, Bitbucket), and monitoring systems (Datadog, PagerDuty) all use webhooks. Master the pattern once, apply it everywhere.
The Polling Problem
To understand why webhooks matter, start with the alternative. Imagine you want notifications when someone opens issues in your GitHub repositories. The naive solution: poll the GitHub API every 30 seconds and check for new issues.
import time
import requests
API_URL = "https://api.github.com/repos/your-user/your-repo/issues"
def poll_new_issues(poll_interval=30):
last_seen_id = None
while True:
print("Checking for new issues...")
response = requests.get(
API_URL,
params={"state": "open", "per_page": 1},
timeout=10,
)
response.raise_for_status()
issues = response.json()
if issues:
newest = issues[0]
issue_id = newest["id"]
if issue_id != last_seen_id:
print(f"New issue: #{newest['number']} - {newest['title']}")
last_seen_id = issue_id
time.sleep(poll_interval)
if __name__ == "__main__":
poll_new_issues()
This script works, but it fails in production:
- Waste: 2,880 requests per day per repository whether anything happened or not. Most return empty results.
- Delay: Issues opened 1 second after your last poll won't be seen for 29 more seconds. Average notification latency: 15 seconds.
- Scale: Monitor 10 repositories? 28,800 daily requests. GitHub's rate limit (5,000 requests per hour for authenticated users) gets consumed by polling, not real work.
- Fragility: Script crashes? Events missed permanently unless you manually audit GitHub's history and backfill.
- Cost: Serverless deployments charge per execution. 28,800 daily Lambda invocations add up fast.
Polling makes sense for learning and prototypes. But production systems need efficiency and reliability. Webhooks provide both.
The Webhook Mental Model
A webhook is an HTTP callback. Instead of your code calling an API repeatedly, the API calls your URL when events occur. The provider POSTs to your endpoint with headers describing the event and a JSON payload containing full details.
Webhook integrations have three components:
- Event source: The service where events happen (GitHub, Stripe, Twilio).
- Webhook receiver: Your HTTP endpoint that accepts POSTs and validates authenticity.
- Event consumer: Your application logic that turns events into actions (send Slack messages, update databases, trigger workflows).
When GitHub detects a new issue, it immediately POSTs to your webhook URL. Your Flask endpoint receives the request, validates the signature, stores the event in your database, and returns 200 OK within milliseconds. A background worker picks up the stored event, extracts issue details, formats a Slack message, and posts the notification. Total time from event to notification: typically under 2 seconds.
Contrast this with polling: average 15-second delay, 2,880 wasted requests per day, constant rate limit pressure. Webhooks eliminate all three problems. Events arrive immediately, your app only responds when needed, and rate limits apply to real work rather than empty checks.
Why Webhooks Matter Professionally
Webhook integration skills separate developers who consume APIs from developers who build production integrations. Companies hiring for backend, infrastructure, or integration engineering roles expect candidates to understand event-driven architectures. Webhooks are the foundational pattern.
Every major platform uses webhooks for critical workflows:
- Payment processing: Stripe, PayPal, and Square notify you when charges succeed, subscriptions renew, or disputes open. You can't poll payment APIs fast enough to provide instant checkout confirmation pages.
- Communication platforms: Slack, Discord, and Twilio use webhooks to notify your apps when messages arrive, calls complete, or SMS messages get delivered.
- Version control: GitHub, GitLab, and Bitbucket send webhooks for every push, pull request, issue, and release. CI/CD pipelines depend on these hooks to trigger builds.
- Monitoring and alerting: Datadog, PagerDuty, and Sentry webhook your on-call systems when incidents occur. Response time matters.
"How would you design a system to notify users instantly when payments succeed?"
Wrong answer: "Poll the payment API every few seconds to check payment status."
Strong answer: "Configure a webhook endpoint that Stripe POSTs to when payment events occur. The endpoint validates the HMAC signature, stores the event in a database for audit trails, returns a fast 200 OK to avoid timeouts, then a background worker processes the event and sends the user notification. This eliminates polling waste, provides instant notifications, and creates a reliable audit log of all payment events."
The GitHub Activity Notifier demonstrates all the patterns interviewers expect: signature verification (HMAC + shared secrets), idempotent processing (handle duplicate deliveries safely), fast response times (acknowledge quickly, process slowly), and event normalization (decouple provider-specific JSON from business logic). These patterns apply to every webhook integration you'll build professionally.
Learning Objectives
By the end of this chapter, you'll be able to:
- Explain why polling doesn't scale and when webhooks are the better choice.
- Build Flask endpoints that receive webhook POSTs and respond within timeout constraints.
- Verify webhook authenticity using HMAC SHA-256 signatures with shared secrets.
- Design idempotent handlers that tolerate duplicate deliveries safely.
- Implement fast-acknowledge, slow-process patterns with database queues and background workers.
- Test webhook receivers locally with ngrok and debug production failures using delivery logs.
- Deploy a complete GitHub Activity Notifier that sends real-time Slack alerts.