39.7 Scaling WebSocket Services: Sticky Sessions and Redis Pub/Sub

Right, so you’ve built a single-server WebSocket handler. It’s beautiful. It works. You feel like a genius. Then you try to deploy a second instance behind a load balancer, and suddenly User A on server 1 is sending messages into the void, trying to reach User B who is happily connected to server 2. Your brilliant real-time app has become a masterclass in disappointment. Welcome to the distributed systems party; it’s messy, and everyone’s here.

39.6 nhooyr.io/websocket: A Modern Alternative to Gorilla

Alright, let’s talk about the new kid on the block. You’ve probably heard of Gorilla/websocket—it’s been the de facto standard for years. But its maintainers have gracefully placed it into maintenance mode, which is a polite way of saying, “Maybe don’t start your new, mission-critical project with this.” Enter nhooyr.io/websocket (by the brilliant Eliot Nhooyer), a modern library that feels like it was designed specifically for the Go we write today: context-aware, io-friendly, and blessedly straightforward.

39.5 Server-Sent Events (SSE) as a Simpler Alternative

Now, let’s talk about the quiet, unassuming hero of the real-time web: Server-Sent Events, or SSE. While everyone’s busy setting up the plumbing for a full-duplex WebSocket connection, SSE is over there in the corner, effortlessly pushing data to your client with about 90% less drama. It’s the technology you use when you don’t need a full conversation, just a very informative monologue from your server. Think stock tickers, live notifications, or progress updates—that’s SSE’s sweet spot.

39.4 Managing Multiple WebSocket Connections with a Hub

Right, so you’ve got a single WebSocket connection working. It’s cute. You can send “hello” and receive “world.” Now, let’s get real. The whole point of this technology is to handle many connections, all talking to each other in real-time. You’re not building a walkie-talkie for two people; you’re building a party line. And the moment you have more than a handful of clients, the naïve approach—a global slice of connections and a for loop to broadcast—will absolutely fall on its face. It’ll be slow, prone to race conditions, and about as elegant as a donkey on roller skates.

39.3 Reading and Writing Messages in a WebSocket Handler

Right, so you’ve got your WebSocket connection open. Congratulations, the hard part is over. Now for the fun part: actually using the damn thing. This is where we move from handshakes and protocols to the actual business of shoving data back and forth. It’s simple in theory, but Go’s concurrency model means we get to do it the right way, which is both a blessing and a curse. Let’s break it down.

39.2 gorilla/websocket: The Standard WebSocket Library

Right, let’s talk about gorilla/websocket. If you’re doing WebSockets in Go, this is the library you reach for. It’s not technically the standard library, but it might as well be. It’s the de facto standard, battle-tested, and frankly, it’s excellent. The Go team themselves even maintains a link to it on the official golang.org website, which is about as close to a royal seal of approval as you get in our world.

39.1 WebSocket Protocol: Upgrading an HTTP Connection

Right, so you want real-time communication. You’ve tried long-polling and it felt like a hack from 2005. You’ve heard about Server-Sent Events (SSE) and they’re cool, but they’re a one-way street. You need a proper, full-duplex, real-time channel. That’s where WebSockets come in, and the first thing you need to understand is that it all starts with a slightly awkward handshake—an HTTP upgrade. Think of it like this: HTTP is a polite, transactional conversation. “I ask, you answer, we’re done.” WebSockets want to turn that into a pub where you can just shout updates at each other continuously. But you can’t just barge into the pub yelling; you have to ask the bouncer (the server) nicely to change venues. This asking is the HTTP Upgrade request.

92.7 Choosing Between REST, GraphQL, WebSockets, and SSE

Alright, let’s cut through the noise. You’re not here for a fluffy marketing comparison. You’re building something, and you need to know which of these tools to pull out of your toolbox and when. Choosing between REST, GraphQL, WebSockets, and SSE isn’t about finding the “best” one; it’s about matching the right communication pattern to the job. Using the wrong one is like using a hammer to screw in a lightbulb—messy, inefficient, and frankly, a little embarrassing.

92.6 Server-Sent Events (SSE) with Flask and FastAPI

Right, so you want to push data from your server to your client. You’ve probably heard of WebSockets, and they’re great for a full-duplex chat application. But what if your problem is simpler? What if the server just needs to talk to the client, and the client just needs to listen? That’s where Server-Sent Events (SSE) comes in. It’s the less-famous, hyper-efficient, “I-have-one-job-and-I-do-it-perfectly” cousin of WebSockets. It uses a simple, long-lived HTTP connection, and it’s built right into the browser with the EventSource API. No need for a hefty library. It’s elegant, it’s simple, and it’s tragically underused.

92.5 Django Channels: WebSockets in Django

Right, so you’ve decided you want your Django app to do more than just politely wait for HTTP requests and send back responses. You want it to talk back. You want real-time. And for that, my friend, you need to have a chat with the outside world using WebSockets. Django’s built-in request-response cycle is brilliant, but it’s a monologue. WebSockets are a conversation. And to handle that conversation in Django, you need Channels.

92.4 WebSockets: The websockets Library

Right, so you’ve decided you need real-time, two-way communication. Good for you. REST polling is for chumps and people who hate their server’s sanity. You’re reaching for WebSockets, and in the Python world, that almost certainly means the websockets library. It’s the workhorse. It’s brilliant, but it has opinions, and you need to understand them or it will quietly, and politely, ruin your day. Let’s get one thing straight: websockets is an asynchronous library. If you’re still running a synchronous Flask dev server with threading, turn back now. You need an async ecosystem—asyncio at its core, and probably an ASGI server like Uvicorn or Daphne. This isn’t a limitation; it’s the only sane way to handle thousands of persistent, mostly-idle connections without setting your RAM on fire.

92.3 Ariadne: Schema-First GraphQL

Right, so you’ve decided to go schema-first with GraphQL in Python. Good. You’ve avoided the siren song of writing a bunch of resolver code first and then trying to remember what the API surface was supposed to be. That way lies madness and breaking changes. Instead, we’re using Ariadne, which insists you define your schema in the GraphQL Schema Definition Language (SDL) first. This is the way. It’s a contract, and you’re nailing it to the door before you even think about the implementation. Let’s get into it.

92.2 Strawberry: Code-First GraphQL with Type Hints

Right, so you’ve decided to build a GraphQL API in Python. Good choice. You’ve probably looked at the landscape and seen graphene, which is fine, but it feels a bit… declarative in a clunky way. You define your schema in a language that’s not quite Python, using classes that are a bit verbose. It works, but it doesn’t feel great. Enter Strawberry. It’s the “code-first” GraphQL library that actually embraces modern Python, specifically type hints, to make your schema definition not just tolerable, but genuinely pleasant. The core idea is brilliantly simple: your GraphQL schema is a direct reflection of your Python type-annotated classes and functions. No redundant schema language. It’s just Python.

92.1 GraphQL Fundamentals: Queries, Mutations, Subscriptions

Right, let’s get this straight. You’ve probably been sold GraphQL as the one true way to unshackle your frontend from the tyranny of rigid REST endpoints. And for the most part, that’s true. But it’s not magic. It’s a language, a specification, and like any language, you can use it to write poetry or to create incomprehensible, nested monstrosities that haunt your dreams. I’m here to help you write the poetry.

— joke —

...