IT242 Software Design and Development

Software Design and DevelopmentUnit 519 min read

Architectural Design: Styles, Patterns, Trade-offs & Real Systems

Unit 5 of Software Design and Development explores how to structure large-scale software systems using architectural styles (layered, client-server, microservices), design patterns (MVC, Observer), and trade-offs between scalability, maintainability, and performance. It covers real-world examples from Nepali apps (eSew

TAKEAWAYS:

  • Architectural styles (layered, client-server, microservices) define how components interact, each with distinct trade-offs for scalability and complexity.
  • Design patterns (MVC, Observer, Singleton) solve recurring problems in UI, event handling, and resource management—critical for TU exam questions.
  • Non-functional requirements (scalability, security, fault tolerance) drive architectural decisions (e.g., Daraz’s microservices vs. eSewa’s monolith).
  • Traceability matrices link requirements to architectural elements—a must for exam case studies (e.g., mapping Ncell’s billing system needs to a layered design).
  • Trade-off analysis (e.g., consistency vs. availability in CAP theorem) appears in 30% of exam questions; memorize the CAP triangle.
  • Real-world mapping: WhatsApp’s Observer pattern for message broadcasts; Google’s MapReduce for distributed data processing.

1. What is Software Architecture?

Software architecture is the high-level structure of a system, defining:

  • Components (modules, services, layers)
  • Connectors (APIs, message queues, databases)
  • Configuration (how components interact and data flows)

Why it matters: Poor architecture leads to technical debt (e.g., Daraz’s early monolith slowed feature additions). Good architecture enables:

  • Scalability (handling 100K+ users like Pathao)
  • Maintainability (eSewa’s modular payments system)
  • Fault isolation (Ncell’s redundant servers for 99.9% uptime)

2. Architectural Styles: How Systems Are Structured

Architectural styles are predefined templates for organizing components. Below are the top 5 styles from the TU syllabus, ranked by exam frequency.

A. Layered (N-Tier) Architecture

Definition: A vertical stack where each layer has a single responsibility. Common layers:

  1. Presentation (UI: web/mobile)
  2. Application (business logic)
  3. Persistence (data access)
flowchart TD
    A["Presentation Layer\n(UI: Web/Mobile)"] -->|"HTTP/REST"| B["Application Layer\n(Business Logic)"]
    B -->|"SQL/NoSQL"| C["Persistence Layer\n(Database)"]

Real Example: eSewa’s Payment System

  • Presentation: Mobile app/web portal.
  • Application: Validates user credentials, checks balance.
  • Persistence: MySQL database storing transactions. Why layered?
  • Security: Sensitive logic (e.g., OTP validation) stays in the application layer, hidden from the UI.
  • Reusability: The persistence layer can switch from SQL to NoSQL without changing the UI.

Worked Example: Kathmandu Traffic Routes as a Layered System Imagine a traffic management app:

  • Presentation: Google Maps-like UI showing routes.
  • Application: Calculates shortest path using Dijkstra’s algorithm.
  • Persistence: Stores real-time traffic data from sensors. Trade-off:
  • Pros: Easy to debug (isolated layers), standard for TU exams.
  • Cons: Performance bottleneck if layers are poorly optimized (e.g., slow database queries).

B. Client-Server Architecture

Definition: A central server provides services to client devices (mobile, web). Clients request data; the server processes and responds.

flowchart LR
    subgraph Client
        A["Mobile/Web App"]
    end
    subgraph Server
        B["Backend Server"]
        C["Database"]
    end
    A -->|HTTP Request
    (JSON/XML)
    | B
    B -->|HTTP Response
    (JSON/XML)
    | A
    B -->|"SQL/NoSQL Query"| C

Real Example: Ncell’s Mobile Billing Portal

  • Clients: Users’ phones/tablets accessing the portal.
  • Server: Handles authentication, balance checks, and payment processing. Key Idea:
  • Statelessness: Each request from a client is independent (e.g., logging in, checking balance).
  • Scalability: Add more servers horizontally (e.g., Ncell’s cloud servers during Diwali peak).

Worked Example: Daraz’s Order Processing

  1. Client (user) sends a request to Daraz’s server: "Order ID 12345, status?".
  2. Server queries the database: "SELECT status FROM orders WHERE id = 12345".
  3. Server responds: "Status: Shipped". Trade-off:
  • Pros: Simple to implement, works well for monolithic apps.
  • Cons: Single server = bottleneck (e.g., Daraz’s Black Friday crashes if not load-balanced).

C. Microservices Architecture

Definition: A system broken into small, independent services, each with its own:

  • Database
  • Codebase
  • Deployment pipeline
flowchart TD
    subgraph Client
        A["User"]
    end
    subgraph Services
        B["Service A
        (User Auth)"]
        C["Service B
        (Payment)"]
        D["Service C
        (Inventory)"]
        E["Service D
        (Order)"]
    end
    A -->|"API Call"| B
    A -->|"API Call"| C
    A -->|"API Call"| E
    B -->|"API Call"| C
    C -->|"API Call"| D

Real Example: Google’s YouTube

  • Services:
    • Video upload service
    • Recommendation engine
    • Comment service
    • Analytics service Why microservices?
  • Fault isolation: If the comment service crashes, videos still play.
  • Tech diversity: Use Python for recommendations, Go for high-speed APIs.

Worked Example: Pathao’s Ride-Hailing System

  1. User Service: Handles login/signup.
  2. Driver Service: Matches drivers to riders.
  3. Payment Service: Processes Khalti/Nepal Bank transactions. Trade-off:
  • Pros: Scalable (scale only the driver service during peak hours).
  • Cons: Complexity (service discovery, inter-service communication via APIs).

D. Peer-to-Peer (P2P) Architecture

Definition: No central server; nodes (peers) communicate directly. Used for:

  • File sharing (BitTorrent)
  • Decentralized apps (blockchain)
graph TD
    A["Peer 1"] -->|"File Chunk 1"| B["Peer 2"]
    B -->|"File Chunk 2"| C["Peer 3"]
    C -->|"File Chunk 3"| A
    A -->|"File Chunk 4"| D["Peer 4"]

Real Example: Blockchain (Nepal’s Digital Identity Project)

  • Peers: Government servers and citizen devices.
  • No single point of failure: If one node goes down, others validate transactions. Trade-off:
  • Pros: Decentralized, censorship-resistant.
  • Cons: Slow (consensus mechanisms like Proof-of-Work), hard to debug.

E. Event-Driven Architecture

Definition: Components react to events (e.g., user clicks, sensor data) via event queues (Kafka, RabbitMQ).

sequenceDiagram
    participant User
    participant UI
    participant EventQueue
    participant ServiceA
    participant ServiceB
    User->>UI: Clicks "Buy Now"
    UI->>EventQueue: Publish "OrderCreated" event
    EventQueue->>ServiceA: Notify Inventory
    EventQueue->>ServiceB: Notify Payment

Real Example: WhatsApp Messages

  1. User sends a message → event: MessageSent.
  2. Event triggers:
    • Save to database
    • Notify recipient
    • Update last-seen timestamp Trade-off:
  • Pros: Loose coupling (services don’t need to know about each other).
  • Cons: Complex debugging (e.g., tracing a failed event in a queue).

3. Comparing Architectural Styles

Style Best For Scalability Complexity Fault Tolerance Example
Layered Small/medium apps, TU exam questions Medium Low Medium eSewa, bank ATMs
Client-Server Monolithic apps, legacy systems Medium Low Low (single server) Ncell billing portal
Microservices Large-scale, high-growth apps High High High Google, Netflix
P2P Decentralized apps, blockchain High Very High Very High Bitcoin, IPFS
Event-Driven Real-time systems, IoT High High Medium WhatsApp, stock markets

4. Design Patterns for Architecture

Design patterns are proven solutions to common architectural problems. The TU syllabus emphasizes:

A. Model-View-Controller (MVC)

Problem: Separate UI logic from business logic. Solution:

  • Model: Data and business logic (e.g., User class).
  • View: UI (e.g., login form).
  • Controller: Handles user input (e.g., LoginController).
ModelControllerView
MVC interaction flow (arrows show data/update direction)

Real Example: Daraz’s Product Page

  • Model: Product class (name, price, stock).
  • View: HTML/CSS showing the product.
  • Controller: Handles "Add to Cart" button clicks.

Worked Example: eSewa’s Transaction Flow

  1. User clicks "Pay" → Controller receives request.
  2. Model checks balance and deducts amount.
  3. View updates to show "Payment Successful."

B. Observer Pattern

Problem: Notify multiple components when data changes (e.g., stock prices). Solution:

  • Subject: Holds data (e.g., StockMarket).
  • Observers: React to changes (e.g., NewsFeed, MobileApp).
sequenceDiagram
    participant Subject as StockMarket
    participant Observer1 as NewsFeed
    participant Observer2 as MobileApp
    Subject->>Observer1: Register()
    Subject->>Observer2: Register()
    Subject->>Observer1: Notify("Price: 1000")
    Subject->>Observer2: Notify("Price: 1000")
    Observer1->>Observer1: Update Display
    Observer2->>Observer2: Push Notification

Real Example: WhatsApp Message Broadcast

  • Subject: Message object.
  • Observers:
    • Save to database
    • Notify recipient’s device
    • Update "Last Seen" status

C. Singleton Pattern

Problem: Ensure only one instance of a critical resource (e.g., database connection). Solution:

class Database {
    private static Database instance;
    private Database() {} // Private constructor
    public static Database getInstance() {
        if (instance == null) {
            instance = new Database();
        }
        return instance;
    }
}

Real Example: Ncell’s Database Connection Pool

  • Only one pool manages all connections to avoid overload.

5. Non-Functional Requirements (NFRs) and Trade-offs

Architectural decisions are driven by NFRs (not user features). Key NFRs:

NFR Definition Architectural Impact Example
Scalability Handle growth (users/data) Microservices > Monolith Daraz’s Black Friday traffic
Availability Uptime (e.g., 99.9%) Redundant servers, load balancers Ncell’s 24/7 service
Security Protect data (e.g., GDPR compliance) Encryption, layered security eSewa’s PCI-DSS compliance
Performance Speed (response time) Caching, CDNs, efficient algorithms Google search latency
Maintainability Easy to update/debug Modular design, clear documentation Open-source projects like Linux

CAP Theorem: A critical trade-off in distributed systems.

  • C: Consistency (all nodes see the same data).
  • A: Availability (system works even if some nodes fail).
  • P: Partition tolerance (system works despite network failures).

Real Example: NEPSE’s Trading System

  • Priority: Availability (trades must go through even if one server fails).
  • Sacrifice: Consistency (delayed updates are acceptable).

6. Architectural Design Process (TU Exam Flow)

  1. Identify Stakeholders: Users, admins, developers (e.g., Daraz: buyers, sellers, logistics).
  2. Gather Requirements: Functional (e.g., "user can track orders") + NFRs (e.g., "99.9% uptime").
  3. Select Architectural Style: Based on requirements (e.g., microservices for scalability).
  4. Decompose System: Break into components (e.g., Pathao: rider service, driver service).
  5. Design Interfaces: Define how components communicate (APIs, message queues).
  6. Evaluate Trade-offs: Use tables like the one above.
  7. Prototype: Build a small-scale model (e.g., mock APIs for TU exams).
  8. Document: Create diagrams (UML, sequence diagrams) and a traceability matrix.
Step 1RequirementsGathering (Functional/Step 2Style Selection(Layered/MicroservicesStep 3PatternApplication (MVC/ObserStep 4Prototype &Trade-off Analysis (CAStep 5Documentation(Diagrams + Decisions)
TU's 5-step architectural design workflow

Worked Example: Designing a Bank Loan System Requirements:

  • Users can apply for loans.
  • Admins approve/reject.
  • NFR: High availability (24/7).

Architecture:

  • Style: Layered (simple, exam-friendly).
  • Components:
    • Presentation: Mobile/web app.
    • Application: Loan approval logic.
    • Persistence: SQL database (for transactions).

Traceability Matrix:

Requirement Architectural Element
User applies for loan Presentation → Application layer
Admin approves loan Application layer (business logic)
High availability Redundant database servers

7. Real-World Applications in Nepal

A. eSewa: Layered Architecture for Payments

  • Why layered?
    • Security: Sensitive data (OTP, card details) stays in the application layer.
    • Compliance: PCI-DSS requires separation of data and logic.
  • Challenge: Scaling during festivals (e.g., Dashain) requires load balancing.

B. Daraz: Microservices for E-Commerce

  • Services:
    • Product catalog
    • Inventory management
    • Payment processing
    • User accounts
  • Why microservices?
    • Independent scaling: Inventory service can handle Black Friday spikes alone.
    • Tech flexibility: Use React for UI, Go for APIs.

C. Ncell: Client-Server for Billing

  • Why client-server?
    • Simple to implement and maintain.
    • Stateless: Each request is independent (good for high concurrency).
  • Challenge: Single server bottleneck during peak hours (solution: add more servers).

D. Pathao: Event-Driven for Ride Matching

  • Events:
    • RiderRequested → Matches with nearest driver.
    • DriverAccepted → Updates ride status.
  • Why event-driven?
    • Real-time updates: Rider and driver see live status.
    • Decoupling: Rider service doesn’t need to know about payment service.

8. Common Pitfalls in Architectural Design

  1. Over-Engineering: Using microservices for a small app (e.g., a bank ATM system).
  2. Ignoring NFRs: Building a high-traffic system without scalability plans (e.g., Daraz’s early monolith).
  3. Tight Coupling: Components too dependent on each other (hard to maintain).
  4. Poor Documentation: Leads to "knowledge silos" (e.g., only one developer understands the system).
  5. Not Planning for Failure: Assuming servers will never fail (e.g., Ncell’s early lack of redundancy).

9. Tools for Architectural Design

Tool Purpose Example Use Case
Lucidchart Draw UML diagrams, sequence diagrams Designing Pathao’s ride-matching flow
Draw.io Free architecture diagrams TU exam mock-ups
Postman Test APIs between microservices Validating Daraz’s product API
Docker Containerize microservices for testing Local development of eSewa’s payment service
Kafka Event-driven communication WhatsApp-like message broadcasts
Draw.ioLucidchartMermaid.jsPlantUMLArchiMate
Popular architectural design tools and their compatibility

In the Real World

  1. eSewa’s Layered Security:

    • Idea: Layered architecture separates UI (mobile app) from sensitive data (bank details in the persistence layer).
    • How it works: Even if a hacker breaches the UI layer, they can’t access the database directly. This is why eSewa complies with PCI-DSS (payment security standards).
  2. Daraz’s Microservices for Black Friday:

    • Idea: Microservices architecture allows Daraz to scale only the inventory and payment services during sales, while keeping other services (e.g., user profiles) unchanged.
    • Real impact: In 2022, Daraz handled 500% more orders without crashing, thanks to independent scaling.
  3. Pathao’s Observer Pattern for Ride Updates:

    • Idea: Observer pattern notifies both the rider and driver in real-time when a ride status changes (e.g., "Driver arrived," "Ride started").
    • How it works:
      • The Ride object (subject) holds the status.
      • The rider’s app and driver’s app (observers) listen for changes.
    • Result: No polling needed—updates are instant, saving battery and improving UX.

Exam Tip

What TU Exams Test (Unit 5)

  1. Definitions and Diagrams (30%):

    • Draw and label layered, client-server, and microservices architectures.
    • Explain MVC, Observer, and Singleton patterns with UML/class diagrams.
    • Example question: "Design a layered architecture for a bank ATM system. Show components and data flow."
  2. Trade-off Analysis (25%):

    • Compare two architectural styles (e.g., "Why would Google use microservices instead of a monolith?").
    • Discuss CAP theorem with real examples (e.g., NEPSE’s trading system).
    • Example question: "A startup wants to build a social media app. Compare layered vs. microservices architectures for their use case."
  3. Case Studies (20%):

    • Map real-world systems (eSewa, Daraz, WhatsApp) to architectural styles/patterns.
    • Example question: "How does Pathao use event-driven architecture? Draw a sequence diagram."
  4. Design Process (15%):

    • Steps to design architecture (gather requirements → select style → decompose → evaluate).
    • Example question: "Design a system for an online exam platform. Show your traceability matrix."
  5. NFRs and Patterns (10%):

    • Link non-functional requirements (scalability, security) to architectural choices.
    • Example question: "Why would a payment system like eSewa use the Singleton pattern for its database connection?"

How to Score Full Marks

  • Diagrams: Always draw mermaid diagrams for architectures/patterns. Label every component.
  • Real Examples: Tie answers to Nepali apps (eSewa, Daraz, Ncell) or global tech (Google, WhatsApp).
  • Trade-offs: Use tables to compare styles (e.g., scalability vs. complexity).
  • Traceability: For case studies, show a matrix linking requirements to architecture.
  • CAP Theorem: Memorize the triangle and give one real example (e.g., NEPSE prioritizes availability over consistency).

Practice Questions for TU Exams

  1. Short Answer:

    • "Explain the Observer pattern with an example from WhatsApp."
    • "What is the CAP theorem? How does it apply to Ncell’s billing system?"
  2. Diagram-Based:

    • "Draw a layered architecture for a hospital management system. Label all layers and show data flow."
    • "Design a microservices architecture for a food delivery app like Swiggy. List 3 services."
  3. Case Study:

    • "eSewa uses a layered architecture. Identify one advantage and one disadvantage of this choice for their payment system."
    • "Why might Daraz switch from a monolith to microservices? Discuss using a comparison table."
  4. Trade-off Analysis:

    • "A startup has limited funds. Compare client-server and microservices architectures for their MVP. Which would you recommend and why?"

Based on the TU BITM syllabus for Software Design and Development (IT242), unit 5.

Discussion

Loading…