Most messaging apps depend on one basic assumption: the internet is available.
When you send a message through WhatsApp, Signal, Telegram, or almost any modern messenger, your phone usually sends that message to a server. The server then delivers it to the recipient.
That model works extremely well.
But what happens when the internet disappears?
Your phone may still have working Bluetooth and Wi-Fi radios. Other phones nearby may also be offline. Somewhere farther away, another phone may still have internet access.
That leads to an interesting question:
Can smartphones help carry encrypted messages for each other until the message reaches either the recipient or a device with internet access?
This article explores an architecture for such a system.
The goal is not to replace the internet.
The goal is to build a messaging system that can continue working when internet connectivity becomes incomplete, unreliable, or temporarily unavailable.
1. The Basic Network
Throughout this article, we will use five devices:
- A — sender, offline
- B — online
- C — offline relay
- D — recipient, initially offline
- E — online
So our starting network looks roughly like this:
A B 🌐 C D E 🌐
A wants to send a message to D.
B and E currently have internet connectivity.
The important part is that these phones are not necessarily all within wireless range of one another.
People move.
Phones disconnect.
New connections appear.
Existing connections disappear.
Because of this, the network cannot depend on one permanent route between A and D.
2. The Scenarios We Need to Handle
Before discussing the routing algorithm, it helps to define the situations the network must support.
Scenario 1: A Can Reach an Online Device
Suppose A can directly communicate with B.
A ───── B 🌐 ───── Server
A sends the encrypted message to B.
B uploads it to the server.
If D is online, the server can deliver it normally.
A → B → Server → D
This is the easiest case.
No complicated peer-to-peer routing is necessary.
Scenario 2: A Cannot Reach the Internet
Suppose A can only communicate with C.
A ───── C B 🌐 E 🌐
A transfers the encrypted message to C.
C currently has no internet access, so it stores the message locally.
Later, C moves near B.
A C ───── B 🌐
C forwards the message to B.
B uploads it to the server.
A → C → B → Server
The important detail is that C did not need to stay connected to A.
C physically carried the message while its owner moved.
This is known as store-carry-forward communication.
Scenario 3: The Server Has the Message but D Is Offline
Suppose the message reaches the server through B:
A → C → B 🌐 → Server
But D currently has no internet connection.
Instead of waiting indefinitely, the server looks at D's most recently reported routing zone.
For example:
D's last known routing zone: ZONE-42
Now suppose E is online and located in or near ZONE-42.
The server can give E an encrypted copy of the message.
Server → E 🌐
E becomes a carrier.
Later, E encounters D.
E ───── D
The complete journey becomes:
A → C → B 🌐 ↓ Server ↓ E 🌐 → D
The message entered the internet through B and left the internet through E.
Scenario 4: Nobody Useful Is Currently Reachable
Consider:
A ───── C B 🌐 D E 🌐
C cannot reach:
- B
- E
- D
- any useful gateway
C simply keeps the encrypted message.
Later, another useful device may appear.
Delivery continues when a new opportunity becomes available.
This means the system cannot guarantee real-time delivery.
It is a delay-tolerant network.
Scenario 5: Multiple Routes Exist
A message may eventually have several possible paths.
For example:
B 🌐 / A ─── C \ E 🌐
Or:
C / \ A ─── B E \ D
Sending the full message through every possible route would increase the chance of delivery.
But it would also create:
- unnecessary radio traffic
- higher battery usage
- duplicated messages
- storage consumption
- possible network congestion
So replication must be controlled.
3. The Core Architecture
The system has two major transport mechanisms:
Internet + Nearby peer-to-peer communication
The application uses whichever route is currently useful.
Conceptually:
Internet │ │ Sender ───── Routing Layer ───── Recipient │ │ Nearby Devices
The general rule is:
- Use direct internet delivery when possible.
- Use nearby devices when internet is unavailable.
- Use an internet-connected nearby device as a gateway.
- If nothing is reachable, store the message.
- Continue delivery when the network changes.
4. Registration and Device Identity
The user registers with the application.
However, the server should not generate the device's private cryptographic identity.
Instead, the phone generates its own key pair.
Device ↓ Generate keys Private Key Public Key
The private key remains on the phone.
The public key is registered with the backend.
The server can then assign a routing identifier:
DEV-A82F91
The structure becomes:
Device Private Key → stays on device Public Key → registered with server Routing ID → assigned by server
This makes it harder for the backend to impersonate a user's physical device.
5. Routing Zones Instead of Exact Location
Location can dramatically improve routing.
But continuously publishing exact GPS coordinates would create an obvious privacy problem.
The network does not necessarily need to know:
25.435823, 81.846427
Instead, the map can be divided into larger zones.
For example:
ZONE-41 ZONE-42 ZONE-43
A zone could represent an area covering several square kilometres.
The device periodically reports only:
Current Routing Zone: ZONE-42
Possible update triggers could include:
- every few hours
- significant movement
- entering another routing zone
- connecting to the internet
- opening the application
The purpose is not live location tracking.
The purpose is to answer a much simpler question:
In what general area might this device be reachable?
6. Message Structure
A message should contain two major sections.
Public Routing Header
Relay nodes need some information to route the packet.
For example:
messageId targetZone createdAt expiresAt hopLimit copyBudget protocolVersion
This information may be visible to relay devices.
Encrypted Payload
Everything sensitive remains encrypted.
senderIdentity recipientIdentity conversationId messageContent attachmentMetadata deliveryMetadata
A relay might therefore see:
Message ID: M82AF91 Target Zone: ZONE-42 Expires: 18:00 Payload: [encrypted]
But it should not see:
Atul → Rahul "Where are you?"
7. Why the Recipient ID Should Not Be Public
Suppose every relay could see:
Recipient: Device-D
Over time, malicious nodes could potentially learn:
- which users communicate
- how frequently they communicate
- where certain recipients are usually reachable
- movement patterns
- social relationships
The message body could be encrypted and still leak useful metadata.
A better system uses an opaque destination token.
For example:
destinationToken: 73AF912C...
Relay devices only know that they have routing information associated with that token.
They do not necessarily know which person owns it.
8. Discovery and Advertising
Nearby networking involves two different operations.
Advertising
Advertising means:
I am an available node.
B 📡
Discovery
Discovery means:
Find available nodes around me.
A 🔎
These operations do not need to run with the same frequency.
A useful strategy is:
Advertising: mostly continuous while mesh mode is active Discovery: adaptive
9. Adaptive Discovery
An isolated device should search more aggressively.
Connected peers: 0 Discovery: frequent
A device already connected to several useful peers can search less often.
Connected peers: 3 Discovery: occasional
A possible policy could be:
0 peers → frequent discovery 1 peer → moderate discovery 2+ peers → occasional discovery Pending message with no useful route → increase discovery Stable internet gateway available → reduce discovery
The exact intervals should be determined through real battery and connectivity testing.
10. Persistent Connections
Once two nodes have established a useful connection, they should not necessarily disconnect immediately.
Suppose:
A ═════ C ═════ B 🌐
If A creates another message five minutes later, the existing route can immediately be reused.
A → C → B
No rediscovery is required.
Persistent connections can therefore reduce:
- delivery latency
- repeated discovery
- connection setup overhead
11. Persistent Connections Are Not Guaranteed
Phones move.
Connections eventually break.
For example:
A ═════ C ═════ B
may become:
A C ═════ B
The network therefore cannot depend entirely on persistent connections.
When a route disappears, the system falls back to:
Store ↓ Carry ↓ Forward
Persistent links improve performance when available.
Store-carry-forward keeps the system functioning when they are not.
12. Why We Should Not Flood Every Message
The easiest routing algorithm would be:
Receive message ↓ Send message to everyone nearby
That would maximize the probability of eventual delivery.
But the number of copies could grow quickly:
1 2 4 8 16 32 64 128 ...
That approach would waste:
- battery
- Bluetooth/Wi-Fi bandwidth
- storage
- processing time
Instead, the system should try to find useful routes before replicating the actual message.
13. Route Discovery Before Sending the Message
Suppose A wants to reach D.
Instead of immediately spreading the encrypted message, A can first send a very small routing query.
For example:
ROUTE_QUERY queryId: Q8219 destinationToken: X92AF expiresAt: +30 seconds hopLimit: 4
Conceptually, A is asking:
Has anyone recently seen or reached this destination token?
Suppose A is connected to C.
A ───── C
C may know that the destination was recently reachable through E.
C replies:
ROUTE_REPLY destinationToken: X92AF nextHop: E lastSeen: 2 minutes ago confidence: 0.87
Only then does A begin forwarding the actual encrypted message toward that route.
14. Learning Routes from Other Messages
This is one of the more interesting parts of the network.
Suppose another unrelated message previously travelled:
C → E → D
C may temporarily remember:
Destination token X92AF was recently reachable through E
Later, A asks C about that destination.
C can answer:
I recently knew a path toward this token.
The previous message content does not matter.
Only temporary reachability information is reused.
Over time, the network gradually develops knowledge about which nodes are likely to encounter which destination tokens.
15. Routes Are Only Hints
Traditional internet routers operate in fairly stable infrastructure.
Phones do not.
A route that exists now may disappear one minute later.
So:
D reachable through E
really means:
D was recently reachable through E.
Routing information should therefore include:
lastSeen confidence estimatedHopCount
For example:
Destination: X92AF Next Hop: E Last Seen: 40 seconds ago Confidence: 0.91
Over time the confidence should decay.
40 seconds ago → 0.91 5 minutes ago → 0.55 20 minutes ago → 0.10
Eventually the route disappears from the cache.
16. Proposed Routing Order
A message should attempt delivery in stages.
Message created ↓ Recipient directly connected? ↓ No Known useful route? ↓ No Limited route discovery ↓ No result Internet gateway available? ↓ No Geographic forwarding ↓ No useful route Store-carry-forward ↓ Limited replication
The actual message is replicated aggressively only when cheaper routing strategies fail.
17. Message Reaches B
Return to our example.
Suppose the topology becomes:
A ───── C ───── B 🌐
A gives the message to C.
A → C
C forwards it to B.
A → C → B
B detects that it has internet access.
B uploads the encrypted message.
A → C → B 🌐 → Server
At this point, the nearby network has successfully connected A to the internet.
18. The Server Searches for D
The server checks whether D is currently online.
If D Is Online
Delivery is straightforward:
Server → D
If D Is Offline
The server looks at D's most recently reported routing zone.
Suppose:
D last reported: ZONE-42
The server then checks for currently online nodes associated with that region.
Node E may currently be available there.
E 🌐 Zone: 42
The server gives the encrypted packet to E.
Server → E
E becomes a carrier.
19. Do Not Send the Message to Every Node in the Zone
The server should not behave like this:
100 nodes online in Zone 42 → send message to all 100
Instead, it should maintain a small number of useful carriers.
For example:
Desired carriers: 3
Suppose:
E carries M100 F carries M100 G carries M100
Now another node H becomes available.
The server does nothing.
Already enough carriers.
This prevents unnecessary server-originated replication.
20. Geographic Forwarding
The routing zone gives the message a general direction.
Suppose E carries a message for ZONE-42.
If E encounters another device already inside Zone 42, that device may be a useful carrier.
If E encounters someone travelling far away from the target area, forwarding may be less useful.
Future routing scores could consider:
distance to target zone movement direction recent destination encounters route confidence battery level message age connection quality
A first prototype can use a much simpler model.
21. Do Not Delete Messages Just Because They Leave the Zone
Suppose a carrier moves outside Zone 42.
Immediately deleting the message would be dangerous.
The carrier may:
- return to Zone 42 later
- encounter another useful node
- find an internet gateway
- meet the recipient somewhere else
The target zone is also based on potentially old information.
A better policy is:
Far from target → reduce replication Moving toward target → increase usefulness Inside target → high delivery priority Message expired → delete
The zone should influence routing.
It should not behave like a hard geographic wall.
22. E Eventually Finds D
Eventually:
E ───── D
The two devices establish a connection.
After synchronization, E determines that D is the intended destination for the encrypted packet.
E sends the message.
E → D
Only D can decrypt the encrypted payload.
The complete route may therefore have been:
A │ ▼ C │ ▼ B 🌐 │ ▼ Server │ ▼ E 🌐 │ ▼ D
This is the key idea behind the whole architecture.
The message used different networks for different parts of its journey.
23. Delivery Acknowledgement
Once D receives the message successfully, it creates a signed acknowledgement.
DELIVERY_ACK messageId: M100 status: DELIVERED recipientProof: [...]
The acknowledgement tells the network:
M100 has reached its destination. Stop trying to deliver it.
24. The Server Receives the ACK
E has internet access.
So:
D → E 🌐 → Server
The server changes:
M100 ACTIVE
to:
M100 DELIVERED
Immediately after that:
- no new copies are created
- online carriers can be told to delete their copy
- pending server-side forwarding stops
25. What About Offline Copies?
Suppose another branch still exists.
C → F → G
F and G are offline.
They do not yet know that D already received the message.
That is unavoidable.
A disconnected network cannot instantly share global state.
Eventually one of several things happens.
Case 1
The delivery acknowledgement reaches them.
DELIVERY_ACK → delete M100
Case 2
They reconnect to the server.
Server: M100 already delivered
They delete it.
Case 3
They meet another node that already knows M100 was delivered.
They delete it.
Case 4
The message expires.
They delete it.
26. Delivery Tombstones
Nodes should temporarily remember that a message has already been delivered.
For example:
Message: M100 State: DELIVERED Tombstone expires: 24 hours
The encrypted payload itself can be deleted.
Only a tiny record remains.
Later, suppose another old branch tries to send M100.
The receiving node checks its tombstone:
M100 already delivered.
The stale branch can stop forwarding it.
27. Duplicate Detection
Every message must have a globally unique ID.
For example:
M100-7F92A1...
Suppose a message travels:
A → C → E → C
C receives M100 again.
C checks:
Have I seen M100?
Yes.
So the duplicate is rejected.
This prevents simple forwarding loops.
28. Seeing a Message Before Does Not Mean It Can Never Be Forwarded Again
Suppose C previously sent M100 to:
B E
Later C discovers a completely new device F.
If F does not have M100, forwarding it may still be useful.
C → F
Therefore the system should distinguish between:
I have already seen this message.
and:
This particular peer already has this message.
Those are not the same thing.
29. Message Inventory Synchronization
When two nodes connect, they should not blindly resend their entire databases.
Suppose C has:
M1 M2 M3 M4
E has:
M1 M3
After comparing inventories, E only requests:
M2 M4
Only missing packets are transferred.
For small networks, sets of message IDs may be enough.
At larger scale, compact structures such as Bloom filters could reduce synchronization overhead.
30. Limiting Replication
Every message should have a replication or copy budget.
For example:
copyBudget = 8
A simplified approach could divide the budget.
A begins with:
A: 8
A gives C a copy:
A: 4 C: 4
C later gives E another copy:
C: 2 E: 2
The goal is to prevent unlimited exponential growth.
This is similar to the idea behind Spray-and-Wait routing in delay-tolerant networks.
31. Message Expiration
Every message must eventually die.
Example:
Created: 10:00 Expires: 22:00
Once expired:
Delete payload Stop forwarding
Different packet types can have different expiration times.
For example:
PacketPossible LifetimeRoute query20–60 secondsRouting informationSeveral minutesChat messageHours or daysDelivery ACKSeveral hoursTombstone24–48 hours
These values should be tuned experimentally.
32. Hop Limits
Messages may also have a maximum number of forwarding hops.
Example:
hopCount: 8 maxHops: 20
Each forwarding device increments the value.
When:
hopCount >= maxHops
the message is no longer forwarded.
Hop limits, expiration, and replication budgets protect the network in different ways.
33. Online Nodes Report What They Carry
When a carrier reconnects to the server, it can report:
I currently carry: M100 M211 M991
The server uses that information to control replication.
Suppose the server wants three active carriers for M100.
It already knows:
E → carrying M100 F → carrying M100 G → carrying M100
Another node H appears.
The server does not need to give H another copy.
34. Different Types of Acknowledgement
Not every acknowledgement means the same thing.
The protocol should differentiate them.
Relay ACK
I received the packet.
Gateway ACK
The packet reached an internet-connected gateway.
Server ACK
The backend successfully stored the message.
Delivery ACK
The intended destination device received the message.
Read ACK
The recipient opened the message.
Only a cryptographically valid DELIVERY_ACK should terminate delivery attempts.
Otherwise, a malicious relay could falsely claim that a message was delivered.
35. Replies Do Not Need to Follow the Same Route
Suppose A's message travelled:
A → C → B → Server → E → D
D's reply does not have to travel backward through exactly the same nodes.
It may instead take:
D → F → E → Server → A
Every message is independently routed.
This is important because the physical network may have completely changed by the time the recipient replies.
36. This Is Not a Traditional Mesh Network
A traditional mesh may look like:
A ═ B ═ C ═ D
with relatively stable links.
Our smartphone network may instead look like:
10:00 A ═ C
Then:
10:05 C ═ B
Then:
10:12 B ═ E
Then:
10:20 E ═ D
A and D may never exist in the same fully connected network at the same time.
The message can still arrive.
That is why delay-tolerant networking describes the idea better than traditional mesh networking.
37. Background Processing Does Not Have to Be Heavy
The system may sound computationally expensive.
Most of it can be event-driven.
Instead of constantly looping through the entire database:
while (true) { scanEverything() }
the application responds to events.
Peer discovered → evaluate connection Connection established → synchronize inventories Packet received → validate and store Internet available → synchronize with server Zone changed → update routing information Timer triggered → remove expired packets
CPU processing should therefore remain relatively small.
The larger battery concerns are likely to be:
- Bluetooth/Wi-Fi discovery
- advertising
- maintaining radio connections
- location updates
- background wakeups
The networking policy matters more than raw CPU performance.
38. The Privacy Trade-Off
Geographic routing creates a difficult trade-off.
If every piece of routing information is encrypted, relay nodes cannot make intelligent decisions.
If exact locations are public, privacy becomes unacceptable.
The compromise is to expose only limited routing information.
For example:
Exact recipient location → encrypted Recipient identity → encrypted Message contents → encrypted Coarse destination zone → visible Expiration → visible Routing metadata → visible
This still leaks some metadata.
An observer may know:
This encrypted packet appears to be useful around Zone 42.
That limitation should be acknowledged rather than hidden.
39. Abuse Prevention
A public network where users relay other people's packets can be abused.
Possible attacks include:
- spam
- packet flooding
- storage exhaustion
- battery-drain attacks
- fake routing information
- malicious acknowledgements
- oversized payloads
- identity tracking
Possible protections include:
- packet size limits
- per-device rate limits
- copy budgets
- TTL
- hop limits
- cryptographic signatures
- routing-query limits
- server-side reputation systems
- abusive-device blocking
Abuse resistance would be one of the most important areas for a production implementation.
40. Attachments Are Much Harder Than Text
Text messages are small.
Images and videos are not.
Making random relay devices carry a 10 MB video would be inefficient.
The first version should focus on:
- text messages
- routing packets
- acknowledgements
- small metadata
Large attachments should probably prefer internet gateways.
A later version could selectively relay media when the destination is known to be nearby.
41. Possible Android Stack
A practical Android implementation could use:
Kotlin Jetpack Compose Nearby Connections Room / SQLite Foreground Service Coroutines + Flow Protocol Buffers
A possible structure:
app/ ├── chat/ ├── identity/ ├── crypto/ ├── mesh/ ├── routing/ ├── storage/ ├── transport/ ├── gateway/ └── location/
42. Keep Routing Independent from the Radio Technology
The routing engine should not care whether a packet travels through:
- Nearby Connections
- Bluetooth
- Wi-Fi Direct
- internet
- a simulator
A transport abstraction might conceptually expose:
discoverPeers() connect(peer) send(peer, packet) receivePackets()
Implementations could include:
NearbyTransport InternetTransport SimulatedTransport
This makes the system easier to test and easier to extend later.
43. Simulating the Network
Testing everything using real smartphones would be difficult.
The core network should therefore support simulated nodes.
For example:
A ─ C ─ B 🌐 D E 🌐
A simulator could emulate:
C moves toward B E moves toward D B loses internet D changes zones A reconnects Two network partitions merge
The simulator could test:
- routing
- duplicate detection
- acknowledgements
- TTL
- replication
- delivery cancellation
- route expiration
- gateway selection
Only the actual wireless transport requires physical Android devices.
44. Complete A-B-C-D-E Example
Now combine everything.
Initial State
A Sender Offline B Online C Offline D Recipient Offline E Online
Topology:
A ─ C ─ B 🌐 D E 🌐
A writes:
Where are you?
The message receives:
messageId: M100 targetZone: Z42 expiresAt: 20:00 copyBudget: 6
The actual message contents are encrypted.
A sends M100 to C.
A → C
C can reach B.
A → C → B
B has internet.
B → Server
The server checks D.
D is offline.
D's most recent routing zone is:
ZONE-42
E is currently online in Zone 42.
The server gives E a copy.
Server → E
E stores M100.
Later:
E discovers D.
After synchronizing, E determines that D is the destination.
E → D
D decrypts:
Where are you?
D generates:
DELIVERY_ACK(M100)
E receives the acknowledgement.
Because E has internet:
E → Server
The server marks:
M100 = DELIVERED
No new copies are created.
Existing online carriers are told to remove M100.
Offline copies eventually disappear through:
- delivery ACK propagation
- server synchronization
- tombstones
- expiration
The complete route was:
A │ ▼ C │ ▼ B 🌐 │ ▼ Server │ ▼ E 🌐 │ ▼ D
45. The Interesting Problem Is Not Bluetooth
At first glance, this may sound like:
Send messages through Bluetooth when there is no internet.
That description misses most of the interesting engineering.
The real questions are:
- How do we find a moving recipient?
- How long should routing information remain valid?
- How much location metadata should be visible?
- How many message copies should exist?
- When should a phone become a carrier?
- When should a carrier stop forwarding?
- How should independent network partitions merge?
- How are stale messages removed?
- How do acknowledgements propagate?
- How do we avoid loops?
- How do we minimize battery usage?
- How do we prevent abuse?
Those are networking and distributed-systems problems.
Bluetooth, Wi-Fi, and Nearby Connections are only transport mechanisms underneath them.
46. What Should the First Prototype Build?
The first prototype should not attempt to compete with WhatsApp.
Start with five nodes:
A = sender B = internet gateway C = offline relay D = recipient E = second internet gateway
Build only:
- Device identity
- End-to-end encrypted text messages
- Nearby discovery
- Persistent local connections
- Store-carry-forward
- Unique message IDs
- Duplicate detection
- Message expiration
- Delivery acknowledgements
- Internet gateway upload
- Routing zones
- Server-side zone injection
- Controlled replication
- Route queries
- Basic route caching
A successful demonstration would be:
A has no internet. D has no internet. A sends a message. A → C → B B uploads it. Server sends it to E. E later discovers D. D receives and decrypts it. D returns an acknowledgement. The network stops propagating the message.
That alone demonstrates the core idea.
47. Future Possibilities
If the basic network works, more advanced routing techniques could be explored.
Possible directions include:
- probabilistic routing
- mobility prediction
- privacy-preserving destination tokens
- Bloom-filter route summaries
- battery-aware routing
- social encounter routing
- multi-path routing
- group messaging
- forward secrecy
- adaptive replication
- network-density estimation
- movement-direction prediction
Eventually, the network could make decisions such as:
Node C is statistically much more likely than Node B to encounter the recipient in the next hour.
That would turn the project from a simple messaging application into an experimental mobile networking platform.
Conclusion
Traditional messaging systems usually think in two states:
Online Offline
A delay-tolerant messaging network introduces many states in between:
Online Locally connected Partially connected Temporarily disconnected Carrying a message Waiting for a route Connected again
A message does not need one continuous connection between sender and recipient.
It only needs a sequence of useful opportunities.
Our example:
A → C → B 🌐 → Server → E 🌐 → D
shows exactly that.
Different parts of the journey use different transports.
The payload remains encrypted.
Routing zones provide direction without exposing exact coordinates.
Route queries try to find useful paths before message replication begins.
Replication budgets prevent uncontrolled spreading.
Delivery acknowledgements eventually destroy unnecessary copies.
And when no route exists, the message simply waits.
The idea is not to rebuild the internet between nearby phones.
It is to ask a different question:
If the internet cannot provide a complete path right now, can the devices around us collectively create that path over time?
That is where the project becomes much more interesting than a simple offline messaging app.
