Elective Mobile Application Development

Mobile Application DevelopmentUnit 510 min read

Mobile Agents & P2P: Architectures, Models & Real-World Apps

Unit 5 of Mobile Application Development explores mobile agent systems (autonomous code that migrates across devices) and peer-to-peer (P2P) architectures (decentralized networks like BitTorrent), comparing them to client-server models, analyzing their use in offline-first apps (e.g., Pathao’s ride-matching), and desig

TAKEAWAYS:

  • Mobile agents are autonomous programs that execute on remote hosts, migrate between devices, and persist state—unlike static apps that rely on fixed servers.
  • P2P architectures eliminate central servers by letting peers (devices/users) share resources directly, reducing latency and costs (e.g., WhatsApp’s end-to-end encryption relies on P2P for message routing).
  • Mobile agents excel in disconnected environments (e.g., NTC’s field technicians using agents to pre-process data before syncing), while P2P shines in scalable, low-bandwidth apps (e.g., Khalti’s microtransactions via P2P payment channels).
  • Key trade-offs: Agents add complexity (security, migration overhead) but enable offline resilience; P2P sacrifices centralized control for decentralized robustness.
  • Real-world hybrid models (e.g., Google Drive’s offline editing) use agents for local processing + P2P for syncing changes.
  • Exam focus: Compare architectures (table), design a simple agent/P2P protocol, and analyze a case study (e.g., how Pathao uses P2P for ride-matching).

Core Concepts: Mobile Agents vs. Peer-to-Peer

1. Mobile Agents: Autonomous Code on the Move

Mobile agents are self-contained programs that:

  • Migrate between devices (e.g., a laptop, smartphone, or cloud server).
  • Execute autonomously on remote hosts (no constant server connection needed).
  • Persist state across migrations (unlike stateless HTTP requests).

How They Work:

MigrationState PersistenceMigrationResult ReturnDevice A (Agent Creation)Device B (Execution)Device C (Execution)Cloud Server (Optional)
Mobile Agent lifecycle: creation → migration → execution → state persistence → result return

Example: A field technician for NTC uses a mobile agent to:

  1. Collect network signal data on a smartphone (offline).
  2. Migrate to a nearby base station when online.
  3. Process data locally (e.g., detect outages) before syncing to a central server.

Visual: Agent Migration Steps


2. Peer-to-Peer (P2P) Networks: Decentralized Collaboration

P2P networks eliminate central servers by letting peers (devices/users) directly exchange resources (data, compute power, or services). Key models:

  • Pure P2P: All peers are equal (e.g., BitTorrent).
  • Hybrid P2P: Some peers act as supernodes (e.g., Skype’s early architecture).

How P2P Works (vs. Client-Server):

Feature Client-Server P2P
Control Centralized (server) Decentralized (peers)
Scalability Limited by server Scales with peers
Latency High (server hop) Low (direct peer-to-peer)
Fault Tolerance Single point of failure Resilient (peers can replace failed nodes)
Cost High (server maintenance) Low (peers share resources)

Real-World Example: Khalti’s P2P Payment System

  • Problem: Nepal’s rural areas have poor internet but high mobile penetration.
  • Solution: Khalti uses P2P payment channels to route transactions directly between users’ phones, bypassing banks for small amounts (< Rs. 500). This reduces latency and transaction fees.
  • How:
    1. User A sends Rs. 200 to User B via Khalti app.
    2. Khalti’s P2P network matches A and B directly (if both are online).
    3. If offline, the request is queued until both devices sync (via mobile data or Wi-Fi).

Visual: P2P Payment Routing



Designing Mobile Agent Systems

Worked Example: Offline-First Inventory Check for Daraz

Scenario: Daraz sellers in Kathmandu need to verify stock levels without internet. Use a mobile agent to:

  1. Collect inventory data offline.
  2. Migrate to Daraz’s server when online.
  3. Update the central database.

Steps:

  1. Agent Creation: Seller’s phone creates an agent with current stock (e.g., 10 units of Product X).
  2. Offline Execution: Agent checks local inventory (no internet needed).
  3. Migration Trigger: When the phone connects to Wi-Fi, the agent migrates to Daraz’s server.
  4. Server Processing: Daraz’s server validates the agent’s data and updates the central inventory.
  5. Result Return: Agent sends confirmation to the seller’s phone.

Code Example (Pseudocode):

class InventoryAgent:
    def __init__(self, product_id, initial_stock):
        self.product_id = product_id
        self.stock = initial_stock
        self.status = "offline"

    def check_stock(self):
        # Simulate offline stock check
        self.stock = self.stock - 2  # Sold 2 units
        self.status = "ready_to_migrate"

    def migrate(self, destination_server):
        # Simulate migration to server
        print(f"Agent migrated to {destination_server}. Stock: {self.stock}")
        return self.stock

# Seller's phone
agent = InventoryAgent("P001", 10)
agent.check_stock()  # Offline check
stock_update = agent.migrate("Daraz Server")  # Online migration

Trace Table:

Step Agent State Action Output
1 status="offline" check_stock() stock=8, status="ready"
2 status="ready" migrate("Daraz Server") Prints "Migrated. Stock: 8"
3 (Server-side) Server updates DB DB updated to stock=8

Visual: Agent State After Each Step


Advantages of Mobile Agents:

  • Offline Resilience: Work without constant connectivity (critical for Nepal’s rural areas).
  • Reduced Bandwidth: Only migrate when necessary (e.g., sync once/day).
  • Autonomy: Agents can adapt to network conditions (e.g., retry failed migrations).

Disadvantages:

  • Security Risks: Malicious agents can corrupt data or drain resources.
  • Complexity: Requires agent platforms (e.g., JADE, Aglets).
  • Migration Overhead: Latency if many agents migrate simultaneously.

Designing P2P Protocols

Worked Example: Pathao’s Ride-Matching P2P Model

Scenario: Pathao needs to match riders and drivers without a central server to reduce latency in Kathmandu’s traffic.

P2P Protocol Steps:

  1. Peer Discovery: Riders/drivers broadcast their location and status (e.g., "Rider at Thapathali, needs a car").
  2. Direct Matching: Nearby drivers respond directly to the rider’s phone (P2P).
  3. Route Confirmation: Both parties agree on fare/route via P2P messages.
  4. Payment Handling: P2P microtransactions (like Khalti) settle the fare.

Mermaid Flowchart:

sequenceDiagram
    participant Rider as Rider's Phone
    participant Driver1 as Driver 1's Phone
    participant Driver2 as Driver 2's Phone
    Rider->>+Driver1: "Ride Request (Thapathali → Kantipath)"
    Rider->>+Driver2: "Ride Request (Thapathali → Kantipath)"
    Driver1-->>Rider: "Accept (Fare: Rs. 200)"
    Driver2-->>Rider: "Reject (Too far)"
    Rider->>Driver1: "Confirm Route"
    Driver1->>Rider: "Start Ride"

Why P2P?:

  • Lower Latency: No server hop (critical in Kathmandu traffic).
  • Scalability: Works even if Pathao’s servers are down.
  • Cost-Effective: No need for expensive backend infrastructure.

Comparison with Client-Server:

Feature Pathao’s P2P Model Traditional Client-Server
Matching Speed ~1-2 seconds (direct) ~3-5 seconds (server relay)
Server Load None (peers handle matches) High (all requests go to server)
Fault Tolerance High (peers can match independently) Low (server outage = no matches)

In the Real World

  1. eSewa’s Offline Payments (Mobile Agents)

    • Idea Used: Mobile agents for offline transaction processing.
    • How: When users pay bills (e.g., electricity) offline, eSewa’s agent:
      • Stores the payment request locally.
      • Migrates to eSewa’s server when online.
      • Processes the payment and updates the user’s account.
    • Why: Critical for rural areas with intermittent internet.
  2. WhatsApp’s P2P Messaging (Hybrid P2P)

    • Idea Used: P2P for end-to-end encryption + supernodes for routing.
    • How:
      • Direct P2P chat: Messages go directly from Phone A to Phone B (no WhatsApp server).
      • Group chats: Use supernodes (peers with more bandwidth) to relay messages.
    • Why: Reduces latency and protects privacy (no server can read messages).
  3. NEPSE’s Distributed Trading (P2P for Stock Data)

    • Idea Used: P2P for real-time stock price sync.
    • How:
      • Brokers’ terminals (peers) exchange stock prices directly.
      • If one broker’s connection drops, others fill the gap.
    • Why: Ensures trading continues even if NEPSE’s central servers lag.

Exam Tip: How This Unit is Tested

  1. Compare Architectures (30% weight):

    • Draw a table (like above) comparing mobile agents vs. P2P vs. client-server.
    • Must include: Scalability, latency, fault tolerance, and a real-world example for each.
  2. Design a Simple Protocol (30% weight):

    • Example Question: "Design a P2P protocol for a Daraz seller to verify stock levels without a central server."
    • Your Answer Must:
      • Use a sequence diagram (Mermaid) or flowchart.
      • Show state changes (e.g., "offline → migrated → updated").
      • Include one advantage and one disadvantage of your design.
  3. Case Study Analysis (20% weight):

    • Example Question: "How does Pathao use P2P to reduce ride-matching latency in Kathmandu?"
    • Your Answer Must:
      • Explain the P2P steps (discovery → matching → confirmation).
      • Compare with client-server (use a table).
      • Mention one real-world challenge (e.g., "What if a driver’s phone goes offline?").
  4. Code + Trace (20% weight):

    • Example Question: "Write pseudocode for a mobile agent that checks a bank’s loan interest offline and migrates to the server when online."
    • Your Answer Must:
      • Include a code block (Python/pseudocode).
      • Provide a trace table (like the Daraz example above).
      • Highlight one security risk (e.g., "Malicious agent could alter interest rates").

Pro Tip: For full marks, always:

  • Use visuals (Mermaid diagrams, tables, state diagrams).
  • Tie examples to Nepali apps (eSewa, Khalti, Pathao).
  • End with a real-world trade-off (e.g., "P2P reduces latency but increases security risks").

Based on the TU BSc CSIT syllabus for Mobile Application Development, unit 5.

Discussion

Loading…