Skip to main content

Asynchronous Task Execution In Python

Schedulers became major architechtural component of any software that we use, these asynchrous task executors are behind the emails and notifications, the pop up that greets us on logging in, the repo

Schedulers are a beautiful piece of code. In computer systems, they are as old as operating systems. In real world they are as old as our alarm clocks. In the world of computers, programmers used to schedule an appointment with an operator(a person) to run their code. Later when programmers wanted to take the operators out of their job they wrote scheduling algorithms.

When Operating Systems came into the picture, instead of computer operators it was schedulers that fed programs into the CPU for their execution. Over the years, the number of processing cores increased and so did the complexity of scheduling algorithms. The layers of hardware caches, RAM and hard disks brought up the need for different kinds of scheduling long, medium and short term.

Now, in the era of cloud and distributed systems, schedulers became an indisposable architectural component of any software system. These asynchronous task executors are behind the emails, notifications, the pop-ups that greet us on logging in, and reports that are sent to your email and so on.

Celery, RabbitMQ, Redis, Google Task Queue API, and Amazon’s SQS are major players of task scheduling in distributed environments.

The rest of this blog sheds light on conventional task queue systems, and where asyncio stands, and finally we cover the pros on cons of the major players.

Traditional Task Schedulers

Conventional tasks queues have two programs (a producer and a consumer) with a database acting as a queue. For every task created by the producer an entry is made in the database with a flag NotStarted, Running, Completed, Failed, and so on. At any point task workers (say a never-ending python program) will query this DB and look for incomplete tasks and start running it. It is a simple implementation but it has its own disadvantages.

Disadvantages

  • Maintaining tasks on a DB table means that the table grows based on the number of tasks. It becomes complicated when the DB grows so much that we have to deal the problem of scaling.
  • For every consumer that’s free it queries the DB with task flag Scheduled, to fetch a scheduled task that it can run. The querying becomes costly as the size of the DB grows.

Cron

Cron is the simplest software utility that enables you to run a task asynchronously at a given time. The utility maintains a single file (a table) called crontab. The utility itself is a scheduled job that runs every minute, takes a log of every command that is scheduled to run in the current minute, and runs each command. How cool is that?

Usecases

  1. Backups
  2. Cleaning up temp files
  3. Reminders

Example

I wrote a simple python script to trigger a Mac notification that asks me to take a break every 20 minutes.

import os

def notify(title, text):
    os.system("""
    osascript -e 'display notification "{}" with title "{}"'
    """.format(text, title))

notify("Take a break", "You are sitting for too long")
# > crontab -e
*/20 * * * * python /<path_to_script>/notfication.py

Problems to remember

1. What if you have users across timezones? Whenever we deal with time, we are also dealing with timezone problems. Cron jobs by default runs in the configuration of timezone in the machine it is running, we can override it using TZ environment variable. But cron isn’t suitable if we want to run different tasks at different timezones.

2. What happens if a cron fails? When a script fails on executing a cron job, the error is just logged and the cron waits for the next schedule. This is not the most reliable way of handling errors. We would often want schedulers to retry until a certain threshold before moving on.

3. Scaling - What if the number of tasks to be executed at a given time is very large? - What if a single task occupies a lot of memory?

Code Example - Treasure Hunt

I will be using a treasure hunter program as an example to explain the concepts in the blog. The problem statement is simple.

  1. We have a treasure hunt program with 10000 files with one file containing a word treasure.
  2. The goal of the program is to go through the files and find the treasure.
# make_treasure.py
import random
from pathlib import Path

N = 10_000        # number of files
LINES = 5         # lines per file

def create_treasure(folder="treasure_data"):
    """Create N files; exactly one of them contains the word Treasure."""
    Path(folder).mkdir(exist_ok=True)
    treasure_in = random.randint(0, N - 1)
    for i in range(N):
        word = "Treasure\n" if i == treasure_in else "Not a treasure\n"
        Path(folder, f"file_{i}.txt").write_text(word * LINES)
    return treasure_in

if __name__ == "__main__":
    print(f"treasure is in file_{create_treasure()}.txt")

Asynchronous Python

Asynchronous Python is gaining popularity after the release of asyncio. Though it has got nothing to do with task schedulers, it is important to understand where it stands.

Threading

Python threading is an age-old story. Though it gives an idea of running multiple threads simultaneously, in reality it doesn’t. Why? Because cpython has GIL(Global interpreter locks). Unless your program has a lot of waiting over external (I/O) events, using threading is not of much use. Even when your laptop has multiple cores, you would often find them idle on CPU intensive tasks due to GIL.

The treasure_hunter program implemented using threading would have threads looking through different ranges of files.

N = 10000
treasure_found = False
num_of_threads = 10
count = int(N/num_of_threads)

We have a common flag treasure_found for all threads to set.

def find_treasure(start, end):
    logging.debug(f"{start}, {end}")
    global treasure_found
    for i in range(start, end):
        if treasure_found:
            return
        with open(f"treasure_data/file_{i}.txt", "r") as f:
            if f.readlines()[0] == "Treasure\n":
                treasure_found = i
                return


start_time = time.time()

threads = [threading.Thread(target=find_treasure, args=[i, i+count])
           for i in range(0, N, count)]
[thread.start() for thread in threads]
[thread.join() for thread in threads]

print("--- %s seconds ---" % (time.time() - start_time))
print (f"Found treasure {treasure_found}")

Multiprocessing

The multiprocessing module enables us to overcome the disadvantage of threading. The simplest way to understand this is that the GIL applies only to threads and not to processes, thereby providing us a way to achieve parallelism.

Multiprocessing also works well on CPU intensive tasks as we can use all the cores available independently. When designing a multiprocessing problem, the processes often share a queue from where each process can load tasks for its next execution.

num_of_process = 100

start_time = time.time()
processes = [Process(target=find_treasure, args=[i, int(i+N/num_of_process)])
             for i in range(0, N, int(N/num_of_process))]

[process.start() for process in processes]
[process.join() for process in processes]

print("--- %s seconds ---" % (time.time() - start_time))
print (f"Found treasure {treasure_found}")

Asyncio

In the above two examples, the switching between the threads or processes is handled by the CPU. In certain cases, the developer might be more aware of when a context switch should happen over CPU. Instead of spinning up processes or threads, it lets the program(developer) decide when a program can halt and leave a way for the execution of other tasks.

When I first wrote this post in 2022, the asyncio listing was a gather() call around a read_file() function that I never defined, so you couldn’t run it. Let me fix that. The asyncio I use today also looks different from the 2022 version, because a few things have shipped since:

  • Python 3.11 added asyncio.TaskGroup and asyncio.timeout().
  • Python 3.12 added an eager task factory, which starts a task running immediately instead of waiting for the next loop iteration.
  • Python 3.13 added Queue.shutdown() and asyncio.QueueShutDown, which we will use in the producer-consumer section below (docs).

Everything in this section ran on Python 3.13.18 (x86_64 Linux, 2 cores). You need 3.11 for the TaskGroup and timeout() examples, and 3.13 for the Queue example.

Treasure hunt with TaskGroup and timeout

The Python docs describe TaskGroup as “a more modern alternative” to creating tasks yourself, and say it “provides stronger safety guarantees than gather”: if one task raises an exception, a TaskGroup cancels the remaining tasks, while gather does not. That is exactly what a treasure hunt needs.

Install aiofiles (pip install aiofiles) so the file reads don’t block the event loop, and run make_treasure.py from the treasure hunt section above to create the files. Now the hunt. Ten workers each scan a thousand files, the whole hunt gets five seconds, and create_task() gives us a handle on each worker so we can read its result afterwards.

# hunt.py
import asyncio
import time

import aiofiles

N = 10_000
WORKERS = 10
CHUNK = N // WORKERS


async def find_treasure(start, end):
    """Scan files[start:end]. Return the file number, or None."""
    for i in range(start, end):
        async with aiofiles.open(f"treasure_data/file_{i}.txt") as f:
            if (await f.readline()) == "Treasure\n":
                return i
    return None


async def hunt():
    tasks = []
    try:
        async with asyncio.timeout(5):                 # whole hunt gets 5 seconds
            async with asyncio.TaskGroup() as tg:
                tasks = [tg.create_task(find_treasure(i, i + CHUNK))
                         for i in range(0, N, CHUNK)]
    except TimeoutError:
        print("gave up, the treasure is somewhere else")
        return None
    return next((t.result() for t in tasks if t.result() is not None), None)


start = time.perf_counter()
found = asyncio.run(hunt())
print(f"found treasure in file_{found}.txt in {time.perf_counter() - start:.2f}s")
$ python make_treasure.py
treasure is in file_6625.txt
$ python hunt.py
found treasure in file_6625.txt in 1.14s

A few things worth noticing:

  • asyncio.create_task() (here through tg.create_task()) schedules a coroutine to run on the event loop and returns a Task we can inspect later. Calling find_treasure(...) on its own only builds a coroutine object that never runs.
  • The async with asyncio.TaskGroup() block doesn’t exit until every task inside it has finished.
  • asyncio.timeout(5) wraps the whole block. If the five seconds run out, whatever is still running gets cancelled and a plain TimeoutError comes out, so we don’t need wait_for() around each call.

Honest note on speed. I also timed a plain synchronous for loop that opens the same ten thousand files one after the other. On this machine it finished in about 0.05 seconds, and the aiofiles version above took between 1.1 and 2.3 seconds over three runs. That’s not a mistake. The aiofiles README says it works by “delegating operations to a separate thread pool”, so every tiny read pays for a hop to a thread and back. Asyncio doesn’t make local disk reads faster. It pays off when the program is mostly waiting, which is why the network example further down is the one to take away.

Cancelling work

Right now every worker keeps scanning even after one of them has found the treasure. We can stop the rest by raising an exception from the worker that found it. The TaskGroup cancels the sibling tasks, and the exception comes out of the group wrapped in an ExceptionGroup, which we catch with except*.

# hunt_early.py
import asyncio

import aiofiles

N = 10_000
WORKERS = 10
CHUNK = N // WORKERS


class TreasureFound(Exception):
    def __init__(self, number):
        self.number = number


async def find_treasure(start, end):
    scanned = 0
    try:
        for i in range(start, end):
            async with aiofiles.open(f"treasure_data/file_{i}.txt") as f:
                if (await f.readline()) == "Treasure\n":
                    raise TreasureFound(i)   # TaskGroup cancels every sibling
            scanned += 1
    finally:
        print(f"worker {start:>4}-{end:<4} stopped after {scanned} files")


async def hunt():
    number = None
    try:
        async with asyncio.timeout(5):
            async with asyncio.TaskGroup() as tg:
                for i in range(0, N, CHUNK):
                    tg.create_task(find_treasure(i, i + CHUNK))
    except* TreasureFound as eg:
        number = eg.exceptions[0].number
    return number


print("found in", asyncio.run(hunt()))
worker 6000-7000 stopped after 625 files
worker 1000-2000 stopped after 622 files
worker 2000-3000 stopped after 621 files
worker 5000-6000 stopped after 620 files
worker 3000-4000 stopped after 622 files
worker 4000-5000 stopped after 624 files
worker 7000-8000 stopped after 628 files
worker 9000-10000 stopped after 615 files
worker    0-1000 stopped after 631 files
worker 8000-9000 stopped after 611 files
found in 6625

None of the ten workers reached the end of its range of 1,000 files. The one that found the treasure raised, and the other nine were cancelled at their next await. The finally block ran in all ten, which is why it is the right place for clean-up. The order of the lines changes from run to run.

Two details tripped me up while writing this:

  • return isn’t allowed inside an except* block, which is why hunt() stores the number and returns it afterwards.
  • Cancellation arrives as asyncio.CancelledError at an await. If you catch it, re-raise it when you’re done. The docs say “it should generally be propagated when clean-up is complete”, and warn that TaskGroup and timeout() “might misbehave if a coroutine swallows” it.

You can also cancel a single task by hand with task.cancel():

import asyncio


async def slow_worker():
    try:
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print("worker: cleaning up")
        raise                      # always re-raise


async def main():
    task = asyncio.create_task(slow_worker())
    await asyncio.sleep(0.1)       # let it start
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main: task.cancelled() =", task.cancelled())

    try:
        async with asyncio.timeout(0.2):
            await asyncio.sleep(3600)
    except TimeoutError:
        print("main: timed out")

asyncio.run(main())
worker: cleaning up
main: task.cancelled() = True
main: timed out

task.cancel() only requests cancellation. The task gets a CancelledError the next time it awaits, and await task is how you wait for it to finish unwinding.

aiohttp and aiofiles in practice

The treasure hunt shows the mechanics, but local files are the wrong place to feel the benefit. Network calls are the right one. This example runs a tiny aiohttp server on localhost that takes 0.2 seconds to answer each request (so nothing depends on the internet), fetches 20 pages from it, and saves each page to disk with aiofiles. Install the two libraries with pip install aiohttp aiofiles.

# fetch_save.py
import asyncio
import time
from pathlib import Path

import aiofiles
import aiohttp
from aiohttp import web

URLS = 20
OUT = Path("downloads")


# A tiny local server so the example runs anywhere, with 0.2s of fake latency
async def page(request):
    await asyncio.sleep(0.2)
    return web.Response(text=f"hello from page {request.match_info['n']}\n" * 100)


async def fetch_and_save(session, n, sem):
    async with sem:                                   # at most 5 requests in flight
        async with session.get(f"http://127.0.0.1:8081/page/{n}") as resp:
            body = await resp.text()
    async with aiofiles.open(OUT / f"page_{n}.txt", "w") as f:
        await f.write(body)
    return len(body)


async def main():
    OUT.mkdir(exist_ok=True)
    app = web.Application()
    app.add_routes([web.get("/page/{n}", page)])
    runner = web.AppRunner(app)
    await runner.setup()
    await web.TCPSite(runner, "127.0.0.1", 8081).start()

    sem = asyncio.Semaphore(5)
    start = time.perf_counter()
    async with aiohttp.ClientSession() as session, asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch_and_save(session, n, sem)) for n in range(URLS)]
    print(f"saved {len(tasks)} pages, {sum(t.result() for t in tasks)} bytes, "
          f"in {time.perf_counter() - start:.2f}s")
    await runner.cleanup()

asyncio.run(main())
saved 20 pages, 37000 bytes, in 0.83s

Twenty requests at 0.2 seconds each would take about four seconds one after another. Here the semaphore lets five run at a time, so there are four rounds of 0.2 seconds, which is where the 0.83 seconds comes from. The ClientSession is created once and shared by every task; the aiohttp docs say “Don’t create a session per request.”

asyncio.Queue: a producer-consumer in one process

So far, we’ve decided up front which worker handles which files. A queue turns that around: producers put jobs in, and whichever consumer is free takes the next one. That’s the same shape as the Celery, RQ and RabbitMQ sections below, just inside one process.

# queue_demo.py
import asyncio
import random

async def producer(q, n_jobs):
    for job_id in range(n_jobs):
        await q.put(job_id)              # blocks when the queue is full: back-pressure
    print("producer: all jobs queued")

async def consumer(name, q, results):
    while True:
        try:
            job_id = await q.get()
        except asyncio.QueueShutDown:    # 3.13+: raised once the queue is drained
            return
        await asyncio.sleep(random.uniform(0.01, 0.05))   # pretend work
        results.append((name, job_id))
        q.task_done()

async def main():
    q = asyncio.Queue(maxsize=5)
    results = []
    async with asyncio.TaskGroup() as tg:
        for i in range(3):
            tg.create_task(consumer(f"worker-{i}", q, results))
        await producer(q, 12)
        await q.join()                   # wait until every job is task_done()
        q.shutdown()                     # tell the consumers to stop
    per_worker = {}
    for name, _ in results:
        per_worker[name] = per_worker.get(name, 0) + 1
    print(len(results), "jobs done:", dict(sorted(per_worker.items())))

asyncio.run(main())
producer: all jobs queued
12 jobs done: {'worker-0': 4, 'worker-1': 4, 'worker-2': 4}

How the pieces map to what comes next:

asyncio.QueueTask-queue systems below
q.put()The producer enqueues a task (.delay() in Celery, q.enqueue() in RQ)
q.get() in a consumerA worker picks up a task
q.task_done() and q.join()The worker acknowledges the task (RabbitMQ acks)
maxsizeBack-pressure; a broker has its own limits and policies
q.shutdown()Telling workers to stop gracefully

The difference that matters is where the jobs live. An asyncio.Queue is a Python object in your process’s memory, so if the process dies, the jobs that were waiting in it are gone, and no other machine can help consume them. Celery, RQ and RabbitMQ keep the queue in a separate broker process, so jobs survive a worker restart and many workers on many machines can share the load. That’s why the rest of this post still matters even if you love asyncio. Use asyncio.Queue to organise work inside one program, and reach for a task queue when work has to outlive the program.

Celery

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.

Celery works around two primary components a Queue and a Worker. Queue, also called as message_brokers is a queuing system where you push your tasks to be executed asynchronously. Worker pings the queue once in a while and executes the tasks.

Message Broker

You might often confused between the terms Redis, Celery and RabbitMQ. The Queue component mentioned earlier is not inbuilt in celery. It uses RabbitMq or Redis queuing system. This is why you often find articles that mention all of them.

Worker

When you start a celery worker, it creates a supervisor process which in turn spins up a bunch of other executors these are called execution pool. The number of tasks that can be executed by a celery worker depends on the number of processes in the execution pool. Celery’s concurrency docs cover the pool options (prefork, eventlet, gevent, solo, threads) that you pick with the --pool flag.

Scheduling Tasks in Celery

Unlike crontab, celery by default does not schedule tasks to be run at certain times. To support job scheduling, celery uses Celery Beat.

What happens when a task fails? When a particular task fails, you can configure celery to retry until a particular exception occurs, or set max_retries parameter to enable retrying n times before giving up.

Idempodency

Let’s say you are backing up N-items into a DB as your task. In case two workers pick up the tasks and execute it then it is for the calling function to make sure that the same entry is not made in a DB twice. Workers will have no clue about the side effects of running a particular task.

Redis Queue

Redis by default is an in-memory database and that’s about it. RQ (Redis queue) is a task scheduler to asynchronously execute tasks, which uses redis’ Queue data structure and has an inbuilt worker implementation. The architecture and working is very similar to that of Celery.

N = 10000
num_of_process = 10
count = int(N/num_of_process)

start_time = time.time()
q = Queue(connection=Redis())
results = [q.enqueue(find_treasure, i, i+count)
           for i in range(0, N, count)]

RQ vs. Celery

  1. What if one fine day you wake up and decide to change your Queueing system. Celery supports an extensive line up of message brokers but RQ is built only to work with Redis.
  2. Celery supports subtasks. RQ is simpler: a job can wait on another job with depends_on.
  3. RQ has no priority setting as such. You name queues after priorities (high, medium, low) and point workers at them in that order. Celery supports task priorities too, but the Celery docs say the behaviour depends on the broker and is only approximate on Redis.
  4. RQ is only for python, Celery is not.
  5. Both can schedule jobs: Celery through Celery Beat, and RQ through enqueue_in() and cron-style scheduling (see the RQ docs).
  6. RQ’s default worker forks a child process for every job, so it needs fork(). On Windows, the RQ worker docs tell you to use SimpleWorker, which doesn’t fork. Running RQ inside the Windows Subsystem for Linux also works.

RabbitMQ

RabbitMQ is just a queuing system. It is built over AMQP protocol. In comparison with Celery (which only has worker) and RQ (has both worker and Queue), RabbitMQ has just the queueing system, a robust one.

Architecture

Components

RabbitMQ works on publisher subscriber model. It has 4 major components.

Producers - The code that pushes tasks to the queue. Exchangers - Decides which queue a message should be pushed into. - Direct (Send a message to the queue with respective table) - Topic (Send a message to the queue that matches a specific routing pattern) - Fan out (Send a message to all queues) Queues - Queues are what we have been discussing so far. It has a list of tasks for the workers/consumers. Consumers - Consumers (Worker), also called as workers, are responsible for the actual execution of tasks. At any point of time, workers can be configured to work on a specific queue. RabbitMQ does not have it’s own worker, hence it depends on task workers like Celery.

Fun Fact RabbitMQ, inspite of supporting multiple queues, when used with celery, creates a queue, binding key, and exchange with a label celery, hiding all advanced configurations of RabbitMQ.

Pros

  1. Wonderful documentation
  2. Supports multiple languages
  3. Messages executed can be acknowledged

Cons

  1. Difficult to trace and debug
  2. Errored queues are stored in a different queue
  3. Priorities need setup: RabbitMQ supports priority queues on classic and quorum queues, but the docs recommend only a handful of priority levels on classic queues

Google Task Queue

Update (2026): Google’s current product for this is Cloud Tasks, which describes itself as an App Engine-independent interface to the App Engine Task Queue service. First-generation Task Queue users are pointed to a migration guide. The push and pull modes below describe the original Task Queue API.

Google Task Queue provides two types of queueing mechanism.

  1. Push Mode - The workers dequeue tasks pushed into the queue.
  2. Pull Queue - Your code is responsible for dequeuing the task from the queue and executing it.

Google Pub/Sub

While Pub/Sub is close to asynchrous execution, Google PubSub primarily focuses on message queues and streams. Imagine sending a group message or posting something in a facebook group then every subscriber who is listening to that specific queue should get an alert. These are classic usecases of a Google Pub/Sub.

Where does it differ?

At this point it is valid to ask, why can’t we implement the Pub/Sub model with Task queue, both are asynchronous and both execute tasks right? Google provides us with a clear distinction

Choosing between Cloud Tasks and Cloud Pub/Sub

Both Cloud Tasks and Cloud Pub/Sub can be used to implement message passing and asynchronous integration. Although they are conceptually similar, each is designed for a different set of use case. This page helps you choose the right product for your use case.

Key Differences

The core difference between Cloud Pub/Sub and Cloud Tasks is in the notion of implicit vs. explicit invocation.

Cloud Pub/Sub gives publishers no control over the delivery of the messages save for the guarantee of delivery. In this way, Cloud Pub/Sub supports implicit invocation: a publisher implicitly causes the subscribers to execute by publishing an event. By contrast, Cloud Tasks is aimed at explicit invocation where the publisher retains full control of execution. In particular, a publisher specifies an endpoint where each message is delivered. In a nutshell, Cloud Tasks are appropriate for use cases where a task producer needs to defer or control the execution timing of a specific webhook or remote procedure call. Cloud Pub/Sub is optimal for more general event data ingestion and distribution patterns where some degree of control over execution can be sacrificed.

Choosing a task queue

Here is how everything in this post lines up. I only put things in the table that I checked against the current docs (linked below it).

Where the jobs liveSchedulingPrioritiesReach for it whenWatch out for
asyncio.QueueYour process’s memoryNone built inNone built inYou want to fan out I/O inside one programJobs are lost if the process dies
CeleryAn external broker (RabbitMQ or Redis)Celery BeatSupported, but behaviour depends on the brokerPython workloads that need retries, subtasks and schedulingYou run and tune a broker and workers
RQRedisenqueue_in() and cron-style schedulingName queues by priority (high, low)Small Python-only setups already running RedisRedis only; use SimpleWorker on Windows
RabbitMQIts own brokerNone; it is only the queuePriority queues on classic and quorum queuesMany languages or consumers share one brokerNo worker of its own, so you pair it with Celery or similar
Cloud TasksGoogle-managedThe producer controls timing—You need to defer or control the timing of a specific webhook or RPCExplicit invocation: the producer names the endpoint
Cloud Pub/SubGoogle-managedNone—Event fan-out to whoever subscribesThe publisher has less control over delivery and execution

Sources: Celery routing and priorities, RQ docs, RQ workers, RabbitMQ priority queues and Choosing Pub/Sub or Cloud Tasks.

A rough way to choose:

  1. Waiting on lots of network calls inside one service? asyncio with a TaskGroup, and an asyncio.Queue if you want a fixed number of workers.
  2. Work has to survive restarts, retry, or run on a schedule? A task queue. Celery if you want the full feature set, RQ if you want less machinery and already have Redis.
  3. Other services, possibly in other languages, need to share the queue? RabbitMQ (or a managed equivalent) as the broker.
  4. On Google Cloud? Cloud Tasks when you decide what runs and when, Pub/Sub when you publish an event and don’t care who reacts.

Resources

I referred to a whole bunch of links and read through all the documentation before writing this blog. Here are a bunch of blogs that I really enjoyed.

  1. Asyncio in Python
  2. Python Concurrency
  3. Celery and Celery beat Euro Python
  4. https://www.youtube.com/watch?v=ztyyn7hmcJo
  5. Celery Vs RQ
  6. https://www.fullstackpython.com/task-queues.html
  7. https://www.youtube.com/watch?v=nrzLdMWTRMM
  8. Google Task Queue vs Pub/Sub