Sync vs Async
Wait or not.
When a customer places an order, Shoply must save it, charge the card, send an email, update analytics, and notify the warehouse. Does the customer really need to wait for all of that?

- Save, charge, email
- Analytics, warehouse
- Must the customer wait?
Two ways to do the work
Synchronous means the customer waits until every step is done. If the email service is slow, checkout is slow. If it's down, checkout fails. Asynchronous means we do only the essential steps now, save the order and charge the card, and hand the rest to background workers. The customer gets a fast answer.
Synchronous
- Customer waits for allSlowest step decidesOne failure breaks it
Asynchronous
- Essentials nowThe rest in backgroundFast and resilient
Feeling the difference
Let's time it. Each task takes a tenth of a second. Synchronously, the customer waits for all five tasks. Asynchronously, they wait only for the essentials, and the rest is queued. Run it. The async checkout answers about five times faster.
import time
def work():
time.sleep(0.1)
def checkout_sync():
for task in ["save", "email", "analytics", "warehouse", "receipt"]:
work()
def checkout_async(queue):
work() # save the order
queue.extend(["email", "analytics", "warehouse", "receipt"])
for name, fn in [("sync", checkout_sync), ("async", lambda: checkout_async([]))]:
start = time.perf_counter()
fn()
print(f"{name:>5} checkout: {time.perf_counter() - start:.2f} s")sync checkout: 0.52 s async checkout: 0.10 s
Summary
Synchronous work makes users wait for everything. Asynchronous work does the essentials now, and the rest in the background. Next, the tool that makes async possible. Message queues.
Key takeaways- Sync: wait for all
- Async: essentials now
- Background for the rest