AlgoViz

Push and pull

easy 25 min

When data moves between two parts of a system, somebody has to start the transfer.

Video lesson · Chapter 1 of 5

Is the train platform ready for a new notice?

0:00 / 3:49

Push or pull in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Data has to travel from the part that has it, the producer, to the part that wants it, the consumer. The question of this topic is who starts the journey. If the consumer asks for it, that is pull. If the producer sends it without being asked each time, that is push.

The question is not about direction. In both models the data flows from producer to consumer. Only the first move is different, and that first move decides who must know about whom, who sets the pace, and how old the data is when it arrives.

Why it exists

A consumer that asks cannot know when something new exists, so it asks too often or too late. A producer that sends knows the moment something happens, but it has to remember every consumer, reach them all, and cope with those that are slow or gone.

Each model therefore moves the work to the other side. Naming the model early in a design tells you which problem you have chosen: empty requests and delay, or connections and overload. Many real systems use a little of both.

A short history

  1. October 1984

    RFC 918 describes the Post Office Protocol, with which a workstation fetches mail from a mailbox server. The mail program asks: a pull.

  2. May 1996

    RFC 1945 documents HTTP 1.0. The client sends a request and the server answers it, so the web starts as a pull system.

  3. April 2009

    The W3C publishes the first working draft of Server-Sent Events: one HTTP response that stays open so that the server can keep sending.

  4. April 2011

    RFC 6202 writes down the known issues and best practices of long polling and HTTP streaming, which pages had been using to imitate push.

  5. December 2011

    RFC 6455 standardises the WebSocket protocol: two-way messages over one connection.

  6. December 2016

    RFC 8030 standardises Web Push, so a push service can deliver messages to a browser on behalf of an application.

Words to know

Producer and consumer
The part that has new data, and the part that wants it.
Polling
Asking again and again on a timer. Also called short polling.
Long polling
Asking once, while the server keeps the request open until there is something to say or a time limit passes.
Subscription
A record that says this consumer wants this kind of event.
Cursor
The position of the last event a consumer has handled, sent with the next request.
Back-pressure
A signal from a consumer that it cannot keep up, so the producer must slow down, store or drop.
Fan-out
One event that has to reach many consumers.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask who starts. The consumer asks (pull), or the producer sends (push)

Understand it

Start here

The bread story

Asha wants fresh bread. They can walk to the bakery to ask, or the bakery can bring the bread. Picture a morning of each.

How does the bread reach Asha?
BAKERYAny bread?No, not yetWalk and ask

The bread always travels from the bakery to Asha. What changes is who makes the first move.

Pull

The consumer asks

In a pull system the client sends a request whenever it wants data, and the server answers only when asked. The server does not have to know who its clients are, so any server behind the load balancer can answer.

Pull

Clients outside the system ask a feed API whether there is anything after item 41. The API, which keeps no list of clients, reads the events database and returns an answer that may be empty.
Every transfer starts at the client. The number 41 is the client's cursor: the last item it has handled.

Where you meet pull

  • HTTP and REST calls

    A page load, a search, a form: the browser asks and the server answers.

  • GraphQL and database queries

    The caller describes what it wants and waits for it.

  • File downloads

    The reader picks the moment and can pause.

  • Polling endpoints

    The same question on a timer, such as: is my export ready?

Pull

Short polling and long polling

Short polling repeats the request at a fixed interval. It is simple, and it wastes requests whenever nothing is new. Long polling sends one request, and the server holds it until there is data or a time limit passes. Then the client asks again at once.

Short polling

Item 42 waited for the next poll. Two of the three answers were empty.

Long polling

One open request instead of many empty ones. The client still starts every exchange, so this is pull with a push-like delay.

Numbers

What polling costs

Request rate

requests per second=NT100,000 clients5 s=20,000 per second\text{requests per second} = \frac{N}{T} \qquad \frac{100{,}000 \text{ clients}}{5 \text{ s}} = 20{,}000 \text{ per second}
NN is the number of clients and TT the interval. Polls come at the same rate day and night. If user traffic is added on top, plan that part for a peak of 3 times its average.

Delay and empty answers

average delay≈T2empty share≥1−TU,U=600 s:;1−5600≈99.2%\text{average delay} \approx \frac{T}{2} \qquad \text{empty share} \ge 1 - \frac{T}{U}, \quad U = 600\text{ s}: ; 1 - \tfrac{5}{600} \approx 99.2\%
UU is the average time between updates for one client. With an update every 10 minutes and a poll every 5 seconds there are 120 polls per update, and at least 119 of them are empty.

Choosing a poll interval

IntervalUse it forTrade-off100,000 clients send
100 ms to 1 sNear real-time dashboardsHigh server load1,000,000 to 100,000 per second
5 to 30 sStatus updates, feedsBalanced20,000 to about 3,300 per second
1 to 5 minBackground syncLow load, older dataabout 1,700 to 330 per second
On demandThe user presses refreshLowest load, the user decidesonly what people ask for
Start from the oldest data the user can accept, then check that the load fits. Intervals are rules of thumb.

Push

The producer sends

In a push system the client connects or registers once and says what it wants. After that the server starts every transfer, as soon as there is something to send.

Connect, subscribe, receive

Two messages from the client, then every message starts at the server. Nothing is sent while nothing happens.

Push

An order service sends one event to an event bus. The bus copies it to two push servers, which hold the connections: push server 1 sends to 60,000 clients and push server 2 to 40,000 clients.
A client is connected to one particular push server, so the event must reach every push server that may hold an interested client. A bus does that copying.

Four ways to push

TechnologyWhat it isGoodCosts
WebSocketTwo-way messages over one TCP connectionBoth sides can send at any time, low delayConnection state on one server, heartbeats and reconnects to manage
Server-Sent EventsOne long HTTP response, server to clientSimple, and the browser reconnects by itselfOne direction only, and a proxy that buffers responses can hold events back
Push notificationThe platform's service delivers it: APNs, FCM or Web PushWorks while the app is closed, saves batteryDifferent per platform, small payloads, no promise of delivery time
WebhookAn HTTP request from one server to anotherFits events between companiesThe receiver must expose an endpoint, and the sender must retry
Webhooks have their own topic.

Trade-offs

What each side gains and pays

Pull: gains

  • Simple to build.
  • Works with ordinary HTTP everywhere.
  • The client decides when, and how much.
  • No subscription to remember.
  • Any server can answer, so it is easy to scale.

Pull: costs

  • Empty answers when nothing is new.
  • Later than push by up to one interval.
  • Load grows with clients, not with news.
  • Never quite real time.
  • Bandwidth spent on headers and empty bodies.

Push: gains

  • Data arrives about one network trip after it exists.
  • The lowest delay you can get.
  • No empty requests.
  • The server knows its subscribers, so it can count and target them.

Push: costs

  • Connection or subscription state to keep.
  • Many idle connections still use memory and file handles.
  • A slow client can be overwhelmed.
  • Networks drop connections, so messages get lost unless you can replay them.

Side by side

PushPull
Who startsThe server or producerThe client or consumer
DelayLowest, about one network tripUp to one interval
ResourcesOpen connectionsWork per request
ScalingConnections and fan-out need careStateless servers, easy
ComplexityHigher: state, reconnects, overloadLower: request and answer
Proxies and firewallsMay need settings for long connectionsWorks almost everywhere
Who sets the paceThe producer, unless you add back-pressureThe consumer
Best forLive updatesOn-demand data and APIs

The same 100,000 clients, with push

100,000600 s≈167 messages per second100,000×20 KB=2 GB of memory\frac{100{,}000}{600\text{ s}} \approx 167 \text{ messages per second} \qquad 100{,}000 \times 20\text{ KB} = 2\text{ GB of memory}
One update per client every 10 minutes. The 20 KB per idle connection is an assumption: measure your own server. Push replaces 20,000 requests a second with 167 messages and 2 GB of open connections.

Overload

Back-pressure: when the consumer is slower

A pull consumer is safe by nature: it asks for the next batch when it is done with the last one. A push consumer is not. If events arrive at 100 per second and the consumer handles 60, the gap of 40 per second has to go somewhere.

How long does a buffer last?

t=bufferin−out=1,000100−60=25 secondst = \frac{\text{buffer}}{\text{in} - \text{out}} = \frac{1{,}000}{100 - 60} = 25 \text{ seconds}
A buffer buys time. It only solves the problem if the rush is shorter than that.

Four things a push system can do

  • Slow down

    The consumer grants credits: it says it can take 50 more, and the producer stops at 50.

  • Buffer

    Keep items for a while, with a limit. Without a limit the buffer is a memory leak.

  • Drop or merge

    For prices and positions only the newest value matters, so older ones may be replaced.

  • Disconnect

    Close the slowest client and let it catch up by pulling from its cursor.

Push to a log, pull from the log

An order producer pushes events to a log. A slow consumer at position 400 and a fast consumer at position 1,000 each receive their next batch at their own pace.
The arrows show which way the data moves. Each consumer asks for its next batch and keeps its own position, so the slow one does not hold the fast one back.

Kafka works this way: producers push to the broker, and consumers pull from it. Its documentation names the reason, that a pushed consumer can be overwhelmed, while a pulling one simply falls behind and catches up. The pull can wait for data, so it is a long poll. Delivery and consumer groups belong to asynchronous communication and queues.

Both

Hybrid patterns

Three combinations

  1. 1

    Push a signal, pull the data

    The server pushes a tiny note such as: new message in chat 7. The client then asks for everything after its cursor. Good when notifications are size-limited, as in chat apps.

  2. 2

    Start with long polling, then upgrade

    Begin with the transport that works almost everywhere, test for WebSocket, and switch when it works. Socket.IO upgrades its connections like this by default.

  3. 3

    Push with a pull fallback

    Push gives fresh updates, and a slow periodic pull with a cursor repairs whatever push missed.

Push the signal, pull the data

A push server sends a phone app the signal: you have news. The phone app asks the chat API what is new after 41. The API reads the messages database and answers with messages 42 to 44.
If the signal is lost, the next one, or the periodic pull, brings the same messages. A lost signal costs time, not data.

From long polling to WebSocket

The client works from the first second, and improves when the network allows it.

When a hybrid is worth it

  1. 1

    Old or strict networks

    You need fresh updates, but some clients cannot keep a WebSocket open.

  2. 2

    Size limits

    Push notifications carry only a few kilobytes.

  3. 3

    Unreliable networks

    Phones lose connections, so a message must survive without one.

  4. 4

    Nothing may be missed

    You want the delay of push and the certainty of a stored list.

Reconnects

Never miss an event

Every push connection breaks at some point. Between the break and the reconnect, events happen. The cure is a cursor: number the events, let the client remember the last number it handled, and send it when connecting again.

Catch up after a break

Server-Sent Events build this in: the browser sends the last event id when it reconnects.

Feeds

Push or pull inside a feed

The same choice appears inside a system. When somebody posts, you can push the post into every follower's list (fan-out on write), or let each follower pull it when they open the app (fan-out on read).

Push on writePull on read
Writing a post with 200 followers200 inserts1 insert
Writing a post with 1,000,000 followers1,000,000 inserts1 insert
Opening a feed that follows 300 people1 list readup to 300 reads to merge
Wasted workLists of people who never open the appThe same merge again and again
The usual answer is both: push for ordinary accounts, pull for the few with a huge audience, and merge the two on read. Numbers are examples.

Decide

Which one?

Decision guide

Start from the age of the data, not from the technology.

Examples

SituationModelWhy
Simple create, read, update, deletePullThe user starts every action
Search, page loads, downloadsPullNothing to send until somebody asks
Stock tickers, gamesPushFrequent changes, and only the newest counts
Live chat, notificationsPush, with a pull to catch upDelay matters and nothing may be lost
Many clients, rare updatesPushPolling would be almost all empty, if idle connections are affordable
Email clients, social feedsHybridSignal first, content on open
Shared documents, live dashboardsHybridPush changes, pull the whole state on load and after a break

Summary

The whole topic in one minute.

Pull means the consumer asks. It is simple, keeps no state about clients and lets each consumer set its own pace, but the answer is often empty and always a little late.

Push means the producer sends. It is fast and sends nothing when nothing happens, but it must track consumers, reconnect them, and protect the slow ones. The common middle way is to push a small signal and pull the data with a cursor, so a lost signal costs only time.

  • Push and pull differ in who starts the transfer, not in which way the data flows.
  • Polling costs clients divided by interval, and the data is half an interval old on average.
  • Push sends nothing when nothing happens, but must track, reconnect and protect consumers.
  • Long polling is a pull that waits. Kafka consumers pull.
  • Push a signal and pull with a cursor when speed matters and nothing may be lost.

Sources