Async is The New Default

Why Async?

To Save Memory

Sync → Async

Failure

Warning: code ahead!

Example

async def combine_things(http, u1, u2):
     value1 = await get_json1()
     value2 = await get_json2()
     return combine(value1, value2)

Simultaneous

def combine_things(http, u1, u2):
     (value1, value2), _ = await asyncio.wait([
         get_json1(u1),
         get_json2(u2),
     ])
     return combine(value1, value2)

pipe_vs_seq.svg

Keep-Alive

Nginx → Backend

Request Timeout

with aiohttp.Timeout(10):
    async with session.get(url) as response:
        assert response.status == 200
        return await response.read()

Connection Pool

socket.close()

Task Queues

asyncio.async ≠ celery

Async -> Sync

Pool Size = 1

WebSockets

Browser → Gateway → Backend

GUI

Atomicity

async def transfer(amount, payer, payee, server):
    if not payer.sufficient_funds(amount):
        raise InsufficientFunds()
    payee.deposit(amount)
    log_transfer(amount)
    payer.withdraw(amount)
    await server.update_balances([payer, payee])

Greenlets

async def transfer(amount, payer, payee, server):
    with lock(payer, payee):
        if not payer.sufficient_funds(amount):
            raise InsufficientFunds()
        payee.deposit(amount)
        log_transfer(amount)
        payer.withdraw(amount)
    server.update_balances([payer, payee])

Greenlets: No Monkeypatching!

Q & A