Chat: How a Message Travels
Message flow is the path one message takes from the sender to the receiver. This lesson stays with the high-level design and traces that path.
Tracing one message along its path
One message passes through each stage in turn. The printout lists the stages in the order the message meets them.
stages = ["sender phone", "sender connection server", "chat service", "queue", "worker", "receiver connection server", "receiver phone"]
for i, stage in enumerate(stages, 1):
print(i, stage)Arriving out of order, shown in order
Messages can arrive out of order when separate paths run at different speeds. Sorting by sequence number restores the order they were sent in.
arrivals = [(2, "yes, five works"), (3, "see you then"), (1, "are you free today")]
print("arrival order:", [seq for seq, text in arrivals])
displayed = sorted(arrivals)
for seq, text in displayed:
print(seq, text)Each conversation keeps its own numbers
Two conversations run side by side in this demo. Each one sorts its own messages by its own sequence numbers.
arrivals = [("chat A", 2, "yes, it worked"), ("chat B", 1, "the photos are up"), ("chat A", 1, "did it work"), ("chat B", 2, "thanks")]
by_chat = {}
for chat, seq, text in arrivals:
by_chat.setdefault(chat, []).append((seq, text))
for chat in sorted(by_chat):
for seq, text in sorted(by_chat[chat]):
print(chat, seq, text)Example
sent = ["are you free today", "yes, five works", "see you then", "bring the keys"]
numbered = [(i + 1, text) for i, text in enumerate(sent)]
arrival_order = [numbered[2], numbered[0], numbered[3], numbered[1]]
print("arrival order:", [seq for seq, text in arrival_order])
for seq, text in sorted(arrival_order):
print("display", seq, text)
print("next sequence number:", len(sent) + 1)Key points
- Send path: a message moves from the sender phone through a connection server and the chat service to the receiver connection server.
- Queue handoff: a queue holds the message briefly while a worker picks it up for delivery.
- Sequence number: a number given to each message in one conversation, rising by one with each new message.
- Message ordering: messages are shown in sequence number order, even when they arrive out of order.
- Per conversation: each conversation keeps its own run of sequence numbers.
In this example, the sender numbers each message as it is sent and the network delivers them in a shuffled scripted order. The receiver sorts by sequence number, so the conversation reads exactly as it was written.
Note
ordering is fixed at display time, so a late message still lands in its proper place.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Messages arrive with sequence numbers in a shuffled order. In what order should the app display them?