Software Design and DevelopmentUnit 522 min read
Architectural Design: Styles, Patterns, Trade-offs & Real Systems
Unit 5 of Software Design and Development explores architectural design principles, covering architectural styles (layered, client-server, event-driven), design patterns (MVC, microservices), trade-offs (scalability vs. consistency), and real-world applications in Nepalese and global software systems.
TAKEAWAYS:
- Architectural design defines how components interact in a system (e.g., layered vs. microservices) and directly impacts performance, scalability, and maintainability.
- Four key styles (layered, client-server, pipe-filter, event-driven) solve different problems—choose based on system requirements (e.g., eSewa uses layered for security, Pathao uses event-driven for real-time rides).
- Design patterns like MVC (used in web apps) and microservices (used by Daraz) are reusable solutions to common architectural challenges.
- Trade-offs (e.g., CAP theorem: Consistency vs. Availability vs. Partition tolerance) force critical decisions in distributed systems like Ncell’s billing or NEPSE’s stock trading.
- Non-functional requirements (scalability, security, fault tolerance) drive architectural choices—e.g., banks use three-tier architecture to separate UI, logic, and data.
- Real-world mapping: Trace how Kathmandu’s traffic routes (like a pipe-filter system) or WhatsApp’s message delivery (event-driven) mirror software architectures.
1. What is Architectural Design?
Architectural design is the high-level structure of a software system that defines:
- Components (e.g., modules, services, layers).
- Their interactions (e.g., APIs, message queues, direct calls).
- Non-functional properties (e.g., scalability, security, latency).
Unlike detailed design (which focuses on algorithms or class diagrams), architecture answers:
"How will this system be built to meet its goals?"
Why it matters: Poor architecture leads to technical debt (e.g., Facebook’s early monolith became unmanageable). Good architecture enables:
- Scalability (e.g., YouTube’s microservices handle billions of videos).
- Maintainability (e.g., eSewa’s layered design isolates billing from UI).
- Fault tolerance (e.g., Ncell’s redundant servers prevent outages).
2. Architectural Styles: Choosing the Right Blueprint
Architectural styles are proven templates for organizing systems. Each has strengths and weaknesses. Below are the four core styles from the syllabus, with real-world Nepalese/global examples.
A. Layered (N-Tier) Architecture
Definition: A system divided into horizontal layers, each with a single responsibility. Data flows top-down (e.g., UI → Business Logic → Database).
graph LR
A["Presentation Layer\n(e.g., eSewa Web App)"] --> B["Business Logic Layer\n(e.g., Payment Processing)"]
B --> C["Data Layer\n(e.g., MySQL Database)"]How it works:
- Presentation Layer: Handles user interaction (e.g., eSewa’s payment form).
- Business Logic Layer: Validates rules (e.g., "Is the user’s balance ≥ ₹100?").
- Data Layer: Stores/retrieves data (e.g., SQL queries to the database).
Worked Example: eSewa’s Electricity Bill Payment
- User enters NTC account number (Presentation Layer).
- System checks authentication and balance (Business Logic Layer).
- If valid, deducts amount and updates NTC’s records (Data Layer).
- Returns receipt to the user.
Advantages:
- Separation of concerns: Changes in one layer (e.g., UI) don’t break others.
- Security: Sensitive logic (e.g., passwords) stays in the business layer.
- Reusability: Business logic can be used by multiple UIs (web, mobile).
Disadvantages:
- Performance overhead: Each layer adds latency (e.g., 3-tier vs. direct DB calls).
- Complex transactions: If Layer 2 fails, Layer 1 must retry, adding complexity.
When to use:
- Systems requiring strict security (banks, eSewa).
- Projects where maintainability > raw speed (e.g., government portals).
Real Picture:
Layers in a bank’s online transaction system. (Image: Bartledan (talk), based on a file by User:Foofy, Public domain, via Wikimedia Commons)
B. Client-Server Architecture
Definition: A central server provides services to multiple clients (e.g., web browsers, mobile apps). Clients request data; the server processes and responds.
graph TD
A["Client\n(e.g., Daraz Mobile App)"] -->|"HTTP Request"| B["Server\n(e.g., Daraz Backend)"]
B -->|"JSON Response"| AHow it works:
- Client (e.g., Daraz app) sends a request (e.g., "Show me shoes under ₹2000").
- Server processes the request (queries inventory, applies discounts).
- Server returns data (e.g., product list in JSON format).
Worked Example: Daraz Order Placement
- Client (your phone) sends:
POST /order { "user_id": 123, "items": [...] }. - Server:
- Checks stock availability.
- Validates payment (via Khalti integration).
- Updates database and sends confirmation email.
- Client receives:
{"order_id": 456, "status": "confirmed"}.
Advantages:
- Scalability: Add more servers to handle traffic (e.g., Daraz during sales).
- Centralized data: Easy backups and updates (e.g., Ncell’s customer database).
- Load balancing: Distribute requests across servers (e.g., Google’s data centers).
Disadvantages:
- Single point of failure: If the server crashes, clients can’t access services.
- Latency: Clients depend on network speed (e.g., rural areas in Nepal).
When to use:
- Web/mobile apps (e.g., Pathao, Facebook).
- Systems needing centralized control (e.g., NTC’s billing server).
Real Picture:
How WhatsApp servers handle messages. (Image: Lubaochuan, CC BY-SA 4.0, via Wikimedia Commons)
C. Pipe-Filter Architecture
Definition: Data flows through a series of filters (processes), each transforming it. Used for data processing pipelines (e.g., text processing, media encoding).
graph LR
A["Input Data\n(e.g., Raw Traffic Data)"] --> B["Filter 1\n(Cleaning)"]
B --> C["Filter 2\n(Normalization)"]
C --> D["Filter 3\n(Analysis)"]
D --> E["Output\n(e.g., Report)"]How it works:
- Input: Raw data (e.g., Kathmandu traffic sensor readings).
- Filters:
- Filter 1: Remove noise (e.g., sensor errors).
- Filter 2: Convert to standard format (e.g., JSON).
- Filter 3: Analyze patterns (e.g., "Traffic jams at 8 AM on Ring Road").
- Output: Actionable insights (e.g., "Reroute buses via Budhanilkantha Road").
Worked Example: Kathmandu Traffic Management
- Input: GPS data from 10,000 vehicles.
- Filters:
- Filter 1: Remove duplicate/erroneous data.
- Filter 2: Aggregate by road segment.
- Filter 3: Apply machine learning to predict congestion.
- Output: Dynamic traffic light adjustments (via NTC’s system).
Advantages:
- Modularity: Replace/upgrade filters independently (e.g., swap ML model without changing data input).
- Reusability: Filters can be reused in other pipelines (e.g., same cleaning filter for weather data).
- Parallel processing: Filters can run on separate machines (e.g., cloud servers).
Disadvantages:
- Complex data flow: Hard to debug if a filter fails silently.
- Performance bottlenecks: If one filter is slow, the whole pipeline stalls.
When to use:
- Data processing (e.g., YouTube’s video encoding pipeline).
- ETL (Extract, Transform, Load) systems (e.g., NEPSE’s stock data processing).
Real Picture:
D. Event-Driven Architecture (EDA)
Definition: Components react to events (e.g., user clicks, sensor triggers) via asynchronous messages. Used for real-time systems.
sequenceDiagram
participant User as User
participant App as Pathao App
participant Server as Pathao Server
participant Driver as Driver’s Phone
User->>App: Requests Ride
App->>Server: Publishes "Ride Requested" Event
Server->>Driver: Sends "New Ride Alert" (via Firebase)
Driver->>Server: Accepts Ride
Server->>App: Updates "Ride Assigned"How it works:
- Event Producer: Triggers an event (e.g., "User requests ride" in Pathao).
- Event Bus: Distributes the event to interested components (e.g., driver matching algorithm).
- Event Consumers: React to the event (e.g., notify nearest driver).
Worked Example: Pathao Ride Matching
- Event: User taps "Request Ride" in Pathao app.
- Pathao Server publishes:
{"event": "ride_requested", "user_id": 789, "location": {...}}. - Driver Matching Service (consumer) picks the nearest available driver.
- Notification Service sends a push to the driver’s phone.
- Driver accepts → Pathao updates ride status in real-time.
Advantages:
- Real-time processing: Instant responses (e.g., stock trading, live chats).
- Decoupling: Components don’t need to know about each other (e.g., Pathao’s driver app doesn’t call the ride-matching service directly).
- Scalability: Handle spikes (e.g., Diwali sales on Daraz).
Disadvantages:
- Complexity: Debugging event flows is harder than linear code.
- Ordering issues: Events may arrive out of sequence (e.g., "Driver accepted" before "Ride requested").
When to use:
- Real-time systems (e.g., WhatsApp messages, live sports scores).
- Microservices (e.g., Netflix’s recommendation engine).
Real Picture:
3. Architectural Design Patterns
Patterns are reusable solutions to common architectural problems. Two key patterns from the syllabus:
A. Model-View-Controller (MVC)
Definition: Separates an app into three parts:
- Model: Manages data and business logic (e.g., "User" class in a bank app).
- View: UI (e.g., login form in a web app).
- Controller: Handles input (e.g., "Login button click" → validates credentials).
classDiagram
class Model {
+data
+save()
+validate()
}
class View {
+render()
}
class Controller {
+handleInput()
}
Model "1" --> "1" Controller : updates
Controller --> "1" View : updates
View --> "1" Controller : triggersWorked Example: Khalti Payment App
- View: Shows "Enter Amount" and "Pay" button.
- Controller: Listens for "Pay" click → calls
Model.validate(amount). - Model: Checks balance → returns success/failure.
- View: Updates to "Payment Successful" or "Insufficient Funds".
Advantages:
- Separation of concerns: Easy to update UI without touching business logic.
- Testability: Mock the Model to test Controllers independently.
Disadvantages:
- Tight coupling: Views often depend on Controllers (can lead to spaghetti code).
When to use:
- Web/mobile apps (e.g., Facebook, Instagram).
- Systems needing clear UI-logic separation.
B. Microservices Architecture
Definition: A system split into small, independent services, each with its own:
- Database.
- Codebase.
- Deployment pipeline.
graph TD
A["Frontend\n(e.g., Daraz Web App)"] --> B["User Service\n(Auth, Profiles)"]
A --> C["Order Service\n(Orders, Payments)"]
A --> D["Inventory Service\n(Stock Levels)"]Worked Example: Daraz’s Order System
- User Service: Handles login ("Is this user verified?").
- Order Service: Processes payment ("Charge ₹5000 via Khalti").
- Inventory Service: Checks stock ("Are there 2 units of iPhone 13 left?").
- Frontend: Combines data from all services to show the user their order status.
Advantages:
- Scalability: Scale only the services you need (e.g., Daraz’s payment service during sales).
- Fault isolation: If Inventory Service crashes, Orders still work.
- Tech flexibility: Use different databases/languages per service (e.g., Python for ML, Java for payments).
Disadvantages:
- Complexity: Managing 50+ services is harder than a monolith.
- Network overhead: Services must communicate (e.g., via APIs).
When to use:
- Large-scale systems (e.g., Amazon, Netflix).
- Teams needing independent deployment (e.g., Daraz’s marketing team updates the frontend without touching payments).
4. Trade-offs in Architectural Design
No architecture is perfect. Key trade-offs to consider:
A. CAP Theorem: Consistency, Availability, Partition Tolerance
In distributed systems, you can only guarantee two out of three:
| Property | Definition | Example in Nepal |
|---|---|---|
| Consistency | All nodes see the same data at the same time. | Ncell’s customer database (no two agents see different balances). |
| Availability | System remains operational even if some nodes fail. | Daraz during Diwali (no downtime). |
| Partition Tolerance | System works despite network failures (e.g., internet outages in Kathmandu). | NTC’s billing system during load shedding. |
Worked Example: NEPSE’s Stock Trading System
- Need: High availability (traders can’t afford delays).
- Need: Partition tolerance (networks in Nepal are unreliable).
- Trade-off: Eventual consistency (traders see updated prices after a few seconds).
B. Scalability vs. Complexity
| Approach | Scalability | Complexity | Example |
|---|---|---|---|
| Monolithic | Low (scale entire app) | Low | Early Facebook (hard to scale). |
| Microservices | High (scale per service) | High | Netflix (scales recommendation engine independently). |
| Layered Architecture | Medium | Medium | eSewa (scales UI and DB separately). |
Worked Example: Kathmandu Traffic vs. Pokhara Traffic
- Kathmandu: High complexity (many roads, unpredictable traffic) → Event-driven (adjust lights in real-time).
- Pokhara: Simpler → Layered (fixed traffic rules work).
5. Non-Functional Requirements (NFRs) and Architecture
Architecture must satisfy NFRs (goals beyond features). Key NFRs and their architectural impacts:
| NFR | Definition | Architectural Impact | Example |
|---|---|---|---|
| Scalability | Ability to handle growth (users, data). | Use microservices or load balancers. | Daraz during sales. |
| Security | Protect data and users. | Layered architecture (separate auth layer). | eSewa’s PCI-compliant payments. |
| Fault Tolerance | Stay operational during failures. | Redundant servers, event-driven retries. | Ncell’s 99.99% uptime. |
| Performance | Speed and responsiveness. | Caching (e.g., YouTube’s CDN), pipe-filter for fast data processing. | Pathao’s ride matching (<2 sec). |
| Maintainability | Easy to update and debug. | Clear separation of concerns (e.g., MVC). | Banks updating loan calculators. |
6. Mapping Architectural Styles to Real-World Systems
| System | Architectural Style | Why? | Key Challenge |
|---|---|---|---|
| eSewa | Layered (3-tier) | Strict security (billing data), clear separation of UI and logic. | Performance during peak hours. |
| Pathao | Event-Driven + Microservices | Real-time ride matching, independent scaling of driver/app services. | Driver response latency. |
| Daraz | Microservices | Independent scaling of inventory, orders, and payments. | Data consistency across services. |
| NTC Billing | Client-Server | Centralized billing server for all customers. | Handling 10M+ transactions/day. |
| NEPSE | Pipe-Filter + Event-Driven | Stock data processing pipeline + real-time trading events. | Low-latency requirements. |
| Khalti | Layered + Microservices | Secure payments (layered) + scalable transaction processing (microservices). | Fraud detection in real-time. |
7. Step-by-Step: Designing an Architecture
Scenario: Design a system for a Nepalese food delivery app (like Pathao Food).
Step 1: Identify Requirements
- Functional:
- User can browse restaurants.
- Place orders.
- Track delivery in real-time.
- Non-Functional:
- Handle 10,000 concurrent users during lunch.
- Deliver orders in <30 minutes.
- Secure payment processing.
Step 2: Choose Architectural Style
- Event-Driven for real-time updates (e.g., "Order status changed").
- Microservices for scalability (e.g., separate services for orders, payments, deliveries).
- Layered for security (e.g., separate auth service).
graph TD
A["User App"] --> B["API Gateway"]
B --> C["Auth Service"]
B --> D["Order Service"]
B --> E["Payment Service\n(Khalti Integration)"]
B --> F["Delivery Service"]
D --> FStep 3: Define Data Flow
- User selects food → Event:
{"type": "order_placed", "user_id": 123, "items": [...]}. - Order Service validates stock → publishes
{"type": "order_accepted"}. - Delivery Service assigns a rider → updates
{"type": "rider_assigned", "rider_id": 456}. - Payment Service processes Khalti payment → confirms
{"type": "payment_successful"}.
Step 4: Address Trade-offs
- CAP: Prioritize Availability (users can’t wait for consistency during peak hours).
- Scalability: Use Kubernetes to auto-scale Order Service during lunch.
Step 5: Document the Architecture
Create a diagram (like above) and a decision log:
"Why microservices? Because monolithic would bottleneck during Diwali sales."
## In the Real World
eSewa’s Layered Architecture
- Idea: Three-tier architecture (Presentation → Business Logic → Data).
- How: The business logic layer validates transactions (e.g., "Is the user’s eSewa balance ≥ ₹500?") before updating the database. This isolation prevents UI changes from breaking billing logic.
- Nepalese Impact: During load shedding, the data layer (MySQL) remains stable because the UI layer can retry failed requests.
Pathao’s Event-Driven Ride Matching
- Idea: Event-driven architecture with a message queue (e.g., Kafka).
- How: When a user requests a ride, Pathao’s server publishes an event:
The driver-matching service (a consumer) picks the nearest available driver and publishes:{ "event": "ride_requested", "user_location": {"lat": 27.7000, "lng": 85.3000}, "user_id": 12345 }{ "event": "ride_assigned", "driver_id": 67890, "estimated_time": 5 } - Nepalese Impact: Reduces empty rides by 30% (drivers get alerts instantly).
Daraz’s Microservices for Scalability
- Idea: Microservices (Inventory, Orders, Payments, Reviews).
- How: During the Golden June Sales, Daraz scales only the Orders service (using Docker + Kubernetes) while keeping the Inventory service at baseline. This avoids over-provisioning.
- Global Example: Amazon uses microservices to scale its recommendation engine independently of its checkout system.
## Exam Tip
How this unit is tested in TU/PU/NEB exams:
Definitions and Comparisons (30% of marks):
- Expect questions like:
"Differentiate between layered and microservices architecture with examples from Nepalese software systems."
- Answer Tip: Use a table (like the one above) and real examples (e.g., "eSewa uses layered for security; Pathao uses microservices for scalability").
- Expect questions like:
Diagrams (25% of marks):
- Draw architectural style diagrams (e.g., layered, client-server) with labels.
- Example Question:
"Draw the pipe-filter architecture used in NEPSE’s stock data processing pipeline."
- Answer Tip: Show 3 filters (e.g., "Data Cleaning" → "Normalization" → "Analysis") with arrows.
Scenario-Based Questions (30% of marks):
- Example Question:
"Design the architecture for a Nepalese online exam system (like NEB’s mock tests). Justify your choice of style and address scalability challenges."
- Answer Structure:
- Style: Event-driven (for real-time proctoring events like "Exam started").
- Components: Microservices for Auth, Exam Engine, Proctoring.
- Trade-offs: "We prioritize availability over consistency to prevent exam delays during load shedding."
- Example Question:
Trade-off Analysis (15% of marks):
- Example Question:
"A bank in Nepal must choose between CAP properties for its ATM network. Suggest a configuration and justify."
- Answer Tip: Use the CAP triangle and explain:
"We choose Availability (A) and Partition Tolerance (P) because ATMs must work during internet outages (common in rural Nepal), even if some branches show slightly stale balances (eventual consistency)."
- Example Question:
Common Pitfalls to Avoid:
- Vague answers: Always tie concepts to Nepalese examples (e.g., "Like eSewa’s...").
- Ignoring NFRs: Exams often ask, "How would you ensure scalability in your design?" Answer with specific techniques (e.g., "Use load balancers like Nginx, as Daraz does").
- Overcomplicating: Stick to 2–3 architectural styles per question. Don’t mix microservices with pipe-filter unless asked.
Final Checklist for Full Marks: ✅ Define the architectural style/pattern. ✅ Draw a diagram (Mermaid or labeled). ✅ Give a Nepalese/global example. ✅ Discuss trade-offs (e.g., CAP, scalability vs. complexity). ✅ Link to NFRs (e.g., "This design ensures fault tolerance via...").
Based on the TU BIM syllabus for Software Design and Development (IT242), unit 5.
Discussion
Loading…