Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Channels (Under The Hood)
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Andrew Godwin
November 03, 2016
Programming
1
7.6k
Channels (Under The Hood)
A talk I gave at Django Under The Hood 2016.
Andrew Godwin
November 03, 2016
Tweet
Share
More Decks by Andrew Godwin
See All by Andrew Godwin
Reconciling Everything
andrewgodwin
1
360
Django Through The Years
andrewgodwin
0
270
Writing Maintainable Software At Scale
andrewgodwin
0
490
A Newcomer's Guide To Airflow's Architecture
andrewgodwin
0
390
Async, Python, and the Future
andrewgodwin
2
710
How To Break Django: With Async
andrewgodwin
1
770
Taking Django's ORM Async
andrewgodwin
0
760
The Long Road To Asynchrony
andrewgodwin
0
740
The Scientist & The Engineer
andrewgodwin
1
810
Other Decks in Programming
See All in Programming
なぜSQLはAIぽく見えるのか/why does SQL look AI like
florets1
0
340
ThorVG Viewer In VS Code
nors
0
750
コントリビューターによるDenoのすゝめ / Deno Recommendations by a Contributor
petamoriken
0
190
AI Agent Tool のためのバックエンドアーキテクチャを考える #encraft
izumin5210
6
1.7k
Honoを使ったリモートMCPサーバでAIツールとの連携を加速させる!
tosuri13
1
150
Implementation Patterns
denyspoltorak
0
240
.NET Conf 2025 の興味のあるセッ ションを復習した / dotnet conf 2025 quick recap for backend engineer
tomohisa
0
120
SQL Server 2025 LT
odashinsuke
0
190
TerraformとStrands AgentsでAmazon Bedrock AgentCoreのSSO認証付きエージェントを量産しよう!
neruneruo
4
2.6k
Claude Codeの「Compacting Conversation」を体感50%減! CLAUDE.md + 8 Skills で挑むコンテキスト管理術
kmurahama
1
780
AIエージェントの設計で注意するべきポイント6選
har1101
6
3.2k
Combinatorial Interview Problems with Backtracking Solutions - From Imperative Procedural Programming to Declarative Functional Programming - Part 2
philipschwarz
PRO
0
150
Featured
See All Featured
Building Flexible Design Systems
yeseniaperezcruz
330
40k
Everyday Curiosity
cassininazir
0
120
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
0
2.3k
How to Talk to Developers About Accessibility
jct
1
100
Stop Working from a Prison Cell
hatefulcrawdad
273
21k
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
100
Designing Experiences People Love
moore
143
24k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
390
Building a Scalable Design System with Sketch
lauravandoore
463
34k
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
9.4k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
55
3.2k
エンジニアに許された特別な時間の終わり
watany
106
230k
Transcript
None
Andrew Godwin Hi, I'm Django core developer Senior Software Engineer
at Used to complain about migrations a lot
It's magic.
It's magic.
The Problem 1
The Web is changing.
WebSockets
WebSockets WebRTC Long-polling MQTT Server-Sent Events
Python is synchronous. Django is synchronous.
Synchronous code is easier to write. Single-process async is not
enough.
Proven design pattern Not too hard to reason about
What could fit these constraints?
Loose Coupling 2
Not too tied to WebSockets Not too tied to Django
Well-defined, minimal interfaces
Easy to swap out or rewrite
The Message Bus HTTP Server Message Bus WSock Server Django
Project
What do you send? How do you send it?
ASGI
nonblocking send blocking receive add to group discard from group
send to group
JSON-compatible, dictionary-based messages onto named channels
Concrete Ideas 3
Develop using concrete examples
WebSocket connect receive disconnect accept/reject send
WebSocket websocket.connect websocket.send!abc1234 websocket.receive websocket.disconnect
At-most-once First In First Out Backpressure via capacity Not sticky
No guaranteed ordering No serial processing
HTTP & WS Channel Layer Django Worker HTTP & WS
Django Worker Django Worker Django Worker
{ "text": "Hello, world!", "path": "/chat/socket/", "reply_channel": "websocket.send!9m12in2p", }
Developed and spec'd HTTP WebSocket Rough drafts IRC Email Slack
Please, no. Minecraft Mainframe Terminal
{ "reply_channel": "http.response!g23vD2x5", "method": "GET", "http_version": "2", "path": "/chat/socket/", "query_string":
"foo=bar", "headers": [["cookie", "abcdef..."]], }
At-most-once First In First Out Backpressure via capacity Not sticky
No guaranteed ordering No serial processing
At-most-once First In First Out Backpressure via capacity Not sticky
No guaranteed ordering No serial processing
"order" key on receive messages Connection acceptance
Daphne HTTP/WebSocket Server Channels Django integration asgi-redis Redis backend asgi-ipc
Local memory backend asgiref Shared code and libs
Django-ish 4
It can take several tries to get a nice API.
Consumers based on Views Callable that takes an object Decorators
for functionality Class-based generics
@channel_session def chat_receive(message): name = message.channel_session["name"] message.reply_channel.send({"text": "OK"}) Group("chat").send({ "text":
"%s: %s" % (name, message["text"]), }) Message.objects.create( name=name, content=message["text"], )
Routing based on URLs List of regex-based matches Includes with
prefix stripping on paths More standardised interface
routing = [ route( "websocket.receive", consumers.chat_receive, path=r"^/chat/socket/$", ), include("stats.routing", path="^/stats/"),
route_class(ConsumerClass, path="^/v1/"), ]
Sessions are the only state Sessions hang off reply channels
not cookies Uses same sessions backends Available on the consumer's argument Can also access long-term cookie sessions
@enforce_ordering def receive_consumer(message): Log.objects.create(...)
session = session_for_reply_channel( message.reply_channel.name ) if not session.exists(session.session_key): try: session.save(must_create=True)
except CreateError: # Session wasn't unique raise ConsumeLater() message.channel_session = session
No Middleware New-style middleware half works No ability to capture
sends Decorators replace most cases
View/HTTP Django still there Can intermingle or just use one
type View system is just a consumer now
def view_consumer(message): replies = AsgiHandler()(message) for reply in replies: while
True: try: message.reply_channel.send(reply) except ChannelFull: time.sleep(0.05) else: break
Signals and commands runserver works as expected Signals for handling
lifecycle staticfiles configured for development
Beyond 5
Generalised async communication
Service messaging Security/CPU separation Sync & Async / Py2 &
Py3
Diversity of implementations More web servers More channel layers
More optimisation More efficient bulk sends Less network traffic on
receive
More maintainers More viewpoints, more time
1.0 coming soon Stable APIs for everything except binding
Thanks. Andrew Godwin @andrewgodwin channels.readthedocs.io github.com/andrewgodwin/channels-examples