The Complete Guide to Software Architecture and Design Principles
Introduction to System Design
Software architecture defines the overall structure of an application. System design turns that structure into a practical technical plan.
It answers questions such as:
How will users interact with the application?
Which services and components are required?
How will the system store and retrieve data?
How will components communicate?
What happens when traffic increases?
How will the application respond when a service fails?
How will developers monitor and maintain the system?
A good system design balances several requirements. These include functionality, performance, reliability, security, maintainability, and cost.
Consider an online learning platform. It may need user registration, course management, video delivery, payments, quizzes, notifications, and progress tracking.
A small application might handle these functions in one deployable service. A larger platform may separate some responsibilities into independent services.
The right design depends on actual requirements. A complex architecture does not automatically produce a better system.
1 The System Design Process
A practical system design process follows these steps:
Understand the problem.
Identify users and system boundaries.
Define functional requirements.
Define non-functional requirements.
Estimate expected traffic and data volume.
Select an architecture style.
Design APIs and communication methods.
Select databases and storage systems.
Plan security and failure handling.
Test, measure, and improve the design.
The process should remain iterative. New requirements and performance measurements may change earlier decisions.
Functional and Non-Functional Requirements
Requirements guide every important system design decision.
1 Functional Requirements
Functional requirements describe what a system must do.
For an online learning platform, examples include:
Allow users to create accounts.
Support secure login.
Display available courses.
Allow students to enroll.
Process course payments.
Store quiz results.
Track course progress.
Send enrollment notifications.
These requirements describe application behavior.
2 Non-Functional Requirements
Non-functional requirements describe how well the system must operate.
Common examples include:
| Requirement | Meaning |
|---|---|
| Performance | How quickly the system responds |
| Availability | How often the system remains accessible |
| Scalability | How well it handles increasing demand |
| Security | How it protects data and operations |
| Reliability | How consistently it performs correctly |
| Maintainability | How easily developers can change it |
| Observability | How easily teams can understand system behavior |
| Portability | How easily it can move between environments |
Avoid vague statements such as "the application must be fast."
Use measurable targets instead.
For example:
95% of course catalogue requests should complete within 500 milliseconds under normal load.
The service should meet a monthly availability target of 99.9%.
The platform should support 10,000 concurrent users during planned peak periods.
These figures are illustrative. Production targets should come from business needs, user expectations, and measured system capacity.
3 Quality Attribute Scenarios
A quality attribute scenario makes a non-functional requirement testable.
It describes:
Source: Who or what creates the event?
Stimulus: What happens?
Environment: Under which conditions?
Response: How should the system behave?
Response measure: How will success be measured?
Example:
A sudden increase in course catalogue requests occurs during an enrollment campaign. The platform should increase available application capacity and keep response times within the agreed service target.
This gives engineers a measurable design objective.
Capacity Planning and Workload Estimation
System design should consider expected traffic before selecting infrastructure.
Capacity planning estimates the resources needed to handle application workloads.
1 Important Metrics
Engineers commonly estimate:
Requests per second (RPS)
Concurrent users
Average request size
Database reads and writes
Storage growth
Network bandwidth
Background job volume
Peak traffic periods
2 Basic Request Estimation
Suppose an application receives 600,000 requests per day.
Average requests per second:
600,000 / 86,400 ≈ 6.94 requests per second
The average is about 7 requests per second.
However, average traffic does not reveal peak demand.
If peak traffic is eight times the average:
6.94 × 8 ≈ 55.5 requests per second
The system should be tested against realistic peak workloads, not only daily averages.
3 Storage Estimation
Suppose a platform stores 20,000 records each day. Each record uses approximately 4 KB.
Daily storage:
20,000 × 4 KB = 80,000 KB
That is approximately 80 MB per day using decimal units.
For one year:
80 MB × 365 = 29,200 MB
That is approximately 29.2 GB before indexes, backups, replicas, and storage overhead.
Real storage planning must include those additional requirements.
4 Why Estimation Matters
Capacity estimates help teams:
Choose suitable database configurations.
Plan network capacity.
Estimate cloud spending.
Select caching strategies.
Decide whether asynchronous processing is necessary.
Identify likely bottlenecks before deployment.
Treat estimates as starting assumptions. Production measurements should replace guesses over time.
API Design and Communication Contracts
An API defines how software components communicate.
A clear API contract describes available operations, request formats, response formats, authentication requirements, validation rules, and error behavior.
Good API design helps independent teams build and maintain compatible systems.
1 REST APIs
REST is a widely used architectural style for network-based APIs.
REST APIs commonly use HTTP methods to represent operations.
| HTTP Method | Typical Purpose |
|---|---|
| GET | Retrieve a resource |
| POST | Create a resource or initiate an operation |
| PUT | Replace a resource |
| PATCH | Partially update a resource |
| DELETE | Remove a resource |
Example endpoints for a learning platform:
GET /api/v1/courses
GET /api/v1/courses/101
POST /api/v1/enrollments
GET /api/v1/students/25/progress
PATCH /api/v1/students/25/profile
DELETE /api/v1/enrollments/500Use resource-oriented names. Keep endpoint behavior predictable.
2 Example REST Request
POST /api/v1/enrollments
Content-Type: application/json
Authorization: Bearer <token>Request body:
{
"studentId": 25,
"courseId": 101
}Possible response:
{
"enrollmentId": 500,
"studentId": 25,
"courseId": 101,
"status": "pending"
}The server should validate the request and check whether the user has permission to enroll.
The response should not expose private information or internal implementation details.
3 GraphQL
GraphQL allows clients to request specific fields from a defined data schema.
For example:
query {
course(id: "101") {
title
instructor {
name
}
lessons {
title
duration
}
}
}GraphQL can help applications that need flexible data selection across related resources.
However, it introduces additional design concerns:
Query complexity limits
Authorization at field and object levels
Caching behavior
Resolver performance
Prevention of expensive nested queries
GraphQL is not automatically faster than REST. Its value depends on the application's data access needs.
4 gRPC
gRPC is a remote procedure call framework that commonly uses Protocol Buffers for service contracts.
It supports efficient binary communication and streaming.
It is useful for:
Internal service-to-service communication
High-throughput systems
Strongly defined service contracts
Streaming workloads
Systems with multiple programming languages
Example Protocol Buffers definition:
syntax = "proto3";
service CourseService {
rpc GetCourse (CourseRequest)
returns (CourseResponse);
}
message CourseRequest {
int32 course_id = 1;
}
message CourseResponse {
int32 course_id = 1;
string title = 2;
string description = 3;
}5 Choosing an API Style
| API Style | Strength | Consideration |
|---|---|---|
| REST | Familiar HTTP resource model | Clients may receive more data than needed |
| GraphQL | Flexible data selection | Requires query and resolver management |
| gRPC | Efficient typed communication | Browser and public-client integration may need extra support |
Choose based on clients, communication patterns, performance needs, and team experience.
API Versioning, Pagination, and Error Handling
APIs change as applications grow. Good contracts allow those changes without unnecessarily breaking existing clients.
1 API Versioning
A common approach uses a version in the URL:
/api/v1/courses
/api/v2/coursesVersioning can also use headers or other contract-management methods.
When changing an API:
Document the change.
Identify affected clients.
Maintain compatibility where practical.
Provide a migration period when needed.
Monitor usage of older versions.
Retire old versions through a clear process.
Avoid creating a new version for every small change. Additive, backward-compatible changes are often easier to manage.
2 Pagination
Returning thousands of records in one response can increase memory use, network traffic, and response time.
Pagination divides results into smaller groups.
Example:
GET /api/v1/courses?page=2&limit=20Example response:
{
"data": [],
"page": 2,
"limit": 20,
"total": 125
}For frequently changing datasets, cursor-based pagination can provide more stable navigation.
Example:
GET /api/v1/courses?limit=20&cursor=abc1233 Consistent Error Responses
An API should return useful error information without revealing sensitive internal details.
Example:
{
"error": {
"code": "COURSE_NOT_FOUND",
"message": "The requested course was not found."
}
}Use suitable HTTP status codes:
| Status | Meaning |
|---|---|
| 200 | Request succeeded |
| 201 | Resource created |
| 204 | Request succeeded without a response body |
| 400 | Invalid request |
| 401 | Authentication required or invalid |
| 403 | Access denied |
| 404 | Resource not found |
| 409 | Request conflicts with current state |
| 429 | Too many requests |
| 500 | Unexpected server error |
| 503 | Service temporarily unavailable |
Error messages should help clients understand what happened. They should not expose stack traces, credentials, database details, or private system information.
4 Idempotency
An operation is idempotent when repeating the same request produces the same intended result.
This matters when clients retry requests after network interruptions.
For example, a payment request may reach the server even if the client never receives the response. A retry should not create a second payment.
An idempotency key can help:
POST /api/v1/payments
Idempotency-Key: 7f8a2b91-exampleThe server records the key and associates it with the original result. A repeated request with the same key should return the stored result rather than repeat the operation.
The implementation must also handle key expiration, concurrent requests, and request-body differences.
Database Architecture and Data Modeling
Databases store the information that applications depend on.
Database selection affects consistency, query performance, availability, scalability, and operational complexity.
1 Relational Databases
Relational databases organize data into tables with defined relationships.
Common examples include PostgreSQL, MySQL, and Microsoft SQL Server.
Example:
Students
| student_id | name | |
|---|---|---|
| 25 | Arun | arun@example.com |
| 26 | Meera | meera@example.com |
Courses
| course_id | title |
|---|---|
| 101 | Software Architecture |
| 102 | Database Engineering |
Enrollments
| enrollment_id | student_id | course_id |
|---|---|---|
| 500 | 25 | 101 |
| 501 | 26 | 102 |
The enrollment table connects students with courses.
Relational databases are useful when applications need structured data, relationships, transactions, and well-defined constraints.
2 NoSQL Databases
NoSQL databases use different data models. Common categories include:
Document databases
Key-value databases
Wide-column databases
Graph databases
Example document:
{
"studentId": 25,
"name": "Arun",
"courses": [
{
"courseId": 101,
"progress": 75
},
{
"courseId": 102,
"progress": 40
}
]
}Document databases can work well when records have flexible structures and the application commonly retrieves related data together.
Key-value databases are useful for fast lookups, session data, and caching.
Graph databases are useful when relationships are central to queries, such as recommendation networks or connected knowledge systems.
NoSQL does not mean "no structure." Every production system still needs clear data rules.
3 Relational vs. NoSQL
| Consideration | Relational | NoSQL |
|---|---|---|
| Data structure | Tables and relationships | Documents, keys, columns, or graphs |
| Schema | Usually defined | Often more flexible |
| Relationships | Strong support | Depends on database type |
| Transactions | Mature transaction support | Varies by product |
| Scaling | Vertical and distributed options | Often designed for distributed workloads |
| Common use | Orders, payments, structured records | Flexible content, sessions, large-scale data |
Choose the database that fits the access patterns and consistency requirements. Avoid selecting a database only because it is popular.
4 Database Normalization
Normalization organizes relational data to reduce unnecessary duplication and update problems.
For example, storing a student's details repeatedly in every enrollment record creates duplicate data.
A normalized design stores student information once and references it through a student ID.
Benefits include:
Reduced duplication
More consistent updates
Clearer relationships
Better data integrity
However, highly normalized schemas may require more joins. Some systems use controlled denormalization to improve read performance.
Denormalization should be deliberate. Teams must define how duplicated data stays synchronized.
Indexing, Transactions, and Data Integrity
1 Database Indexes
An index helps a database locate records without scanning every row.
Example:
CREATE INDEX idx_students_email
ON students(email);A query that searches by email may benefit from this index:
SELECT *
FROM students
WHERE email = 'arun@example.com';Indexes can improve reads, but they also:
Consume storage.
Add work to insert and update operations.
Require maintenance.
May not help every query.
Use query plans and measurements to decide which indexes are useful.
2 ACID Transactions
Relational databases commonly support ACID transaction properties.
| Property | Explanation |
|---|---|
| Atomicity | A transaction completes fully or does not take effect |
| Consistency | A transaction preserves defined data rules |
| Isolation | Concurrent transactions are controlled to prevent unwanted interference |
| Durability | Committed data survives according to the database's durability guarantees |
Consider a course purchase. The system may need to record a payment and create an enrollment.
A transaction can protect related database changes when they occur within the same transactional database boundary.
When operations cross multiple services, a single local database transaction is not enough. Distributed workflows need other coordination methods, discussed later.
3 Transaction Isolation
Concurrent transactions can affect one another.
Common isolation levels include:
Read Uncommitted
Read Committed
Repeatable Read
Serializable
Higher isolation can prevent more concurrency anomalies, but it may reduce throughput or increase contention.
Choose an isolation level based on the correctness requirements of the operation.
4 Database Backups and Recovery
A production database needs a recovery plan.
A complete plan should define:
Backup frequency
Backup retention
Encryption
Geographic or account separation
Point-in-time recovery where supported
Recovery time objective (RTO)
Recovery point objective (RPO)
Regular restoration tests
A backup is not proven useful until the team has tested that it can restore the data.
Replication, Partitioning, and Sharding
Large applications may need database designs that distribute data and workloads.
1 Replication
Replication copies data from one database node to another.
A common arrangement uses:
A primary node for writes
One or more replica nodes for reads
Application
|
Database Router
|
Primary Database
|
-----------------
| |
Read Replica 1 Read Replica 2Read replicas can distribute read traffic and support reporting workloads.
However, asynchronous replication may introduce replication lag. A recently updated record may not appear immediately on a replica.
Applications must account for this when users expect read-after-write consistency.
2 Partitioning
Partitioning divides a large table into smaller logical sections.
For example, an event table could be partitioned by month.
Benefits may include:
Faster queries that target specific partitions
Easier retention management
More manageable large tables
Partitioning is not a substitute for good query design. Its benefits depend on the database and query patterns.
3 Sharding
Sharding distributes records across multiple database instances.
A system might distribute users by a user identifier:
User IDs 1–100000 → Shard A
User IDs 100001–200000 → Shard B
User IDs 200001–300000 → Shard CSharding can increase storage and write capacity, but it adds complexity:
Choosing a shard key
Distributing data evenly
Handling cross-shard queries
Rebalancing data
Managing transactions
Maintaining backups and recovery
A poor shard key can create uneven workloads. Start with simpler database scaling methods when they meet the application's needs.
\ Distributed Systems Fundamentals
A distributed system contains components that communicate over a network.
Examples include microservices applications, cloud platforms, payment systems, and large content delivery systems.
Distributed systems introduce challenges that do not appear in the same way inside a single process.
1 Network Latency
Network communication takes time.
A request between two services may involve:
DNS resolution or service discovery
Network connection
Request transmission
Server processing
Database operations
Response transmission
A request that depends on several sequential service calls may become slow even if each individual service is reasonably fast.
Reduce unnecessary calls. Use suitable timeouts, caching, and asynchronous communication where appropriate.
2 Partial Failures
In a distributed system, one component can fail while other components continue working.
For example:
The course service is available.
The payment service is unavailable.
The notification service is delayed.
The platform should define how each operation behaves under these conditions.
A payment failure should not silently create a successful enrollment. A delayed notification should not necessarily prevent a completed enrollment.
Failure handling must reflect business rules.
3 Timeouts
Every network request should have a suitable timeout.
Without a timeout, a service may wait too long for an unavailable dependency.
Set timeouts according to the operation and the overall request budget.
A timeout should also produce a clear outcome. The caller may not know whether the remote operation completed before the connection failed.
This is one reason idempotency matters.
4 Retries
Retries can help recover from temporary failures.
However, uncontrolled retries can increase traffic and make an outage worse.
Good retry policies use:
A limited number of attempts
Exponential backoff
Randomized jitter
Retryable error classification
An overall deadline
Do not retry every failure. Validation errors and permission errors usually require a different response.
38.5 Circuit Breakers
A circuit breaker temporarily stops requests to a failing dependency.
It commonly has three states:
Closed: Requests pass through normally.
Open: Requests are blocked after failures reach a configured threshold.
Half-open: A limited number of test requests check whether the dependency has recovered.
Circuit breakers can prevent repeated failures from consuming application resources.
They should be configured with meaningful thresholds and monitored carefully.
Service Discovery and Load Balancing
Distributed applications need a way to locate services and distribute requests.
1 Service Discovery
Service discovery allows components to find available service instances.
For example:
Enrollment Service
|
Service Discovery
|
-----------------
| | |
Course Course Course
Service Service Service
A B CDiscovery may use DNS, a service registry, platform-native networking, or an orchestrator.
The selected method depends on the deployment environment.
2 Load Balancing
A load balancer distributes incoming traffic across available instances.
Common strategies include:
Round robin
Weighted distribution
Least connections
Health-based routing
Geographic routing
A load balancer should avoid sending traffic to unhealthy instances.
It does not remove the need for application-level capacity planning. If all instances share an overloaded database, adding more application instances may not solve the bottleneck.
Messaging, Queues, and Event Streaming
Not every operation needs an immediate response.
Messaging systems allow services to exchange information asynchronously.
Example:
User Places Order
|
v
Order Service
|
v
Message Queue
|
---------------------
| | |
Payment Inventory Notification
Worker Worker WorkerThe order service can publish a message. Other components process the work independently.
1 Message Queues
A queue stores messages until consumers process them.
Common use cases include:
Sending notifications
Generating reports
Processing uploaded files
Running background tasks
Coordinating independent services
Queues help separate request handling from slower work.
2 Event Streaming
Event streaming platforms support continuous event production and consumption.
They are useful for:
Activity tracking
Audit events
Data pipelines
Analytics
Real-time updates
Integration between services
A queue and an event stream have different delivery and retention models. Choose based on whether messages are task-oriented, replayable events, or both.
3 Message Delivery and Idempotent Consumers
Message delivery may be repeated. Consumers should be designed to handle duplicate messages safely.
A consumer can store processed message IDs and ignore duplicates.
async function processMessage(message) {
const alreadyProcessed =
await processedMessages.exists(message.id);
if (alreadyProcessed) {
return;
}
await database.transaction(async (tx) => {
await applyBusinessChange(tx, message);
await processedMessages.save(tx, message.id);
});
}This is illustrative pseudocode. The business change and processed-message record should be committed atomically where possible.
4 The Transactional Outbox Pattern
A service may need to update its database and publish an event.
If the database update succeeds but event publishing fails, other services may never learn about the change.
The transactional outbox pattern addresses this problem.
The service writes both:
The business data change.
An event record in an outbox table.
Both writes occur in one local database transaction.
A separate publisher reads the outbox and sends events to the message broker. It marks records as published after successful delivery.
This avoids relying on two independent operations succeeding at exactly the same time.
5 The Saga Pattern
A business workflow may involve several services without one shared database transaction.
A saga divides the workflow into local transactions.
For a course purchase:
Create an order.
Reserve a payment.
Confirm enrollment.
Send a confirmation event.
If a later step fails, the system may run compensating actions.
For example, it may release a payment reservation.
Compensation does not always mean restoring the exact previous state. It means performing a business action that addresses the failed workflow.
Use a saga when a process spans multiple services and requires clear recovery rules.
Caching Architecture
Caching stores frequently accessed data in a faster location.
It can reduce database load and improve response times.
1 Common Cache Types
| Cache Type | Purpose |
|---|---|
| Browser cache | Reuse static resources in the user's browser |
| CDN cache | Serve content from geographically distributed locations |
| Application cache | Store frequently used application data |
| Distributed cache | Share cached data across multiple instances |
| Database cache | Reuse database pages or query-related data |
2 Cache-Aside Pattern
In cache-aside, the application checks the cache first.
Application
|
Check Cache
/ \
Hit Miss
| |
Return Query Database
Data |
v
Update Cache
|
v
Return DataExample:
async function getCourse(courseId) {
const cacheKey = `course:${courseId}`;
const cached = await cache.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
const course = await database.findCourse(courseId);
if (!course) {
return null;
}
await cache.set(
cacheKey,
JSON.stringify(course),
{ ttl: 300 }
);
return course;
}This example uses a generic cache interface. Actual method names depend on the selected library.
3 Cache Invalidation
Cached data can become outdated.
Common strategies include:
Time-to-live expiration
Explicit invalidation after updates
Versioned cache keys
Event-based invalidation
For example, when an instructor updates a course title, the application may remove the corresponding cached course record.
Cache invalidation requires careful design. A stale cache can display incorrect information or cause confusing user experiences.
4 Cache Stampede
A cache stampede occurs when many requests attempt to rebuild the same expired cache entry at once.
Possible controls include:
Request coalescing
Short randomized expiration offsets
Background refresh
Locking for cache rebuild operations
Caching should be measured. It adds operational complexity and is not always useful for data that changes frequently.
Scalability and Growth Planning
Scalability describes how a system handles increasing demand.
Two common approaches are vertical and horizontal scaling.
1 Vertical Scaling
Vertical scaling increases the resources of an existing machine.
Examples:
More CPU
More memory
Faster storage
Greater network capacity
Advantages:
Often simpler to implement
May require fewer architectural changes
Useful for systems that do not distribute easily
Limitations:
Hardware has practical limits.
Larger machines can cost more.
A single machine may remain a failure point.
2 Horizontal Scaling
Horizontal scaling adds more machines or service instances.
Incoming Traffic
|
Load Balancer
|
-------------------------
| | |
Server A Server B Server C
| | |
-------------------------
|
Shared Data LayerAdvantages:
Can increase capacity gradually.
Supports distributing workloads.
Can improve resilience when designed correctly.
Challenges:
Requires coordination between instances.
Shared state needs careful management.
Database and network capacity must also grow.
Deployment and monitoring become more complex.
3 Stateless Application Design
Stateless application instances do not depend on local memory to preserve important user session state between requests.
Session data can be stored in a shared database, cache, or secure token-based mechanism.
This makes it easier to distribute requests across instances.
Do not confuse stateless application instances with stateless business processes. An application may still manage long-running workflows and persistent business state.
4 Auto Scaling
Auto scaling adjusts infrastructure capacity based on defined conditions.
Possible signals include:
CPU usage
Memory usage
Request rate
Queue depth
Response latency
Custom application metrics
Scaling rules should include sensible thresholds, cooldown periods, and minimum and maximum capacity.
Scaling too slowly can harm performance. Scaling too aggressively can increase cost or create instability.
Performance Engineering
Performance engineering is the practice of measuring and improving system behavior.
It should begin during design and continue throughout development and operation.
1 Important Performance Metrics
| Metric | What It Measures |
|---|---|
| Latency | Time taken to complete an operation |
| Throughput | Amount of work completed over time |
| CPU utilization | Processor usage |
| Memory usage | Memory consumed by a process |
| Error rate | Percentage of failed operations |
| Database query time | Time spent executing database queries |
| Queue delay | Time messages wait before processing |
| Network utilization | Network capacity being used |
Average latency alone can hide slow requests.
Teams often track percentiles:
p50: Median response time
p95: 95% of requests complete within this time
p99: 99% of requests complete within this time
Tail latency matters because a small percentage of very slow requests can affect user experience and dependent services.
2 Profiling
Profiling helps identify where an application spends time or resources.
Developers can investigate:
Slow functions
Excessive memory allocation
Unnecessary database calls
Lock contention
Network delays
Repeated calculations
Optimize measured bottlenecks rather than guessing.
3 Database Query Optimization
A slow database query can affect the entire application.
Useful techniques include:
Inspecting query execution plans
Adding appropriate indexes
Selecting only required columns
Avoiding unnecessary joins
Limiting result sizes
Using pagination
Reducing repeated queries
Reviewing database connection usage
Example:
EXPLAIN ANALYZE
SELECT course_id, title
FROM courses
WHERE category_id = 5;The exact syntax and output vary by database.
Use execution plans to understand how the database processes a query. Test improvements against realistic data.
4 Concurrency and Resource Management
Applications often process many requests at the same time.
Poor concurrency control can cause:
Database connection exhaustion
Memory pressure
Thread contention
Locking problems
Queue backlogs
Set limits on resource pools. Use backpressure to prevent overloaded components from accepting unlimited work.
A system should reject or defer excess work safely rather than allowing uncontrolled resource consumption.
5 Load Testing
Load testing measures system behavior under expected traffic.
Common test types include:
| Test Type | Purpose |
|---|---|
| Load test | Check behavior under expected demand |
| Stress test | Find limits beyond expected demand |
| Spike test | Examine sudden traffic increases |
| Endurance test | Identify problems during sustained workloads |
| Scalability test | Observe how capacity changes as resources increase |
Use representative test data and realistic user behavior.
A test that sends only one type of request may miss bottlenecks in database writes, background jobs, or third-party integrations.
Service-Level Objectives and Performance Budgets
Performance and reliability targets should be measurable.
1 Service-Level Indicators
A service-level indicator (SLI) is a measurement of service behavior.
Examples:
Successful request percentage
Request latency
Availability
Queue processing delay
Data freshness
2 Service-Level Objectives
A service-level objective (SLO) is a target for an SLI over a defined period.
For example:
99.9% of eligible requests should succeed over a rolling 30-day period.
95% of catalogue requests should complete within 500 milliseconds.
These are example targets, not universal standards.
3 Error Budgets
An error budget represents the amount of unreliability allowed by an SLO.
If a service has a 99.9% availability target, the remaining 0.1% represents its error budget for the measurement period.
Teams can use error budgets to balance feature development and reliability work.
4 Performance Budgets
A performance budget sets limits for specific operations or resources.
Examples:
Maximum API response time
Maximum page transfer size
Maximum database query duration
Maximum background-job delay
Budgets help teams identify regressions before they become major problems.
Practical Case Study: Designing an Online Learning Platform
Consider a platform that offers courses, video lessons, quizzes, payments, and progress tracking.
1 Functional Requirements
The platform must:
Register and authenticate users.
Display a course catalogue.
Support course enrollment.
Process payments through a payment provider.
Deliver video lessons.
Record quiz results.
Track learning progress.
Send notifications.
2 Initial Architecture
A practical starting design could use a modular backend application with a relational database, object storage, and a background job queue.
Users
|
Web / Mobile
|
API Gateway
|
Application Backend
|
--------------------------------
| | | |
Users Courses Enrollment Payments
| | | |
--------------------------------
|
Relational DB
|
------------------
| |
Object Storage Job Queue
| |
Course Videos Background Workers
|
NotificationsThis design keeps related application functions organized while avoiding unnecessary distributed-service complexity.
3 Database Choices
A relational database can store:
User accounts
Course information
Enrollment records
Payment references
Quiz results
Learning progress
Object storage can hold:
Video files
Course documents
Images
Downloadable learning materials
A cache can store frequently requested course information.
The platform should not store raw payment card details unless it has the required security controls and compliance arrangements. A payment provider can handle sensitive payment processing.
4 API Design
Example endpoints:
POST /api/v1/users
POST /api/v1/auth/login
GET /api/v1/courses
GET /api/v1/courses/{id}
POST /api/v1/enrollments
GET /api/v1/users/{id}/progress
POST /api/v1/payments
POST /api/v1/quizzes/{id}/submissionsEach endpoint needs authentication and authorization rules.
For example, a student should only access their own private learning progress unless a specific administrative permission allows otherwise.
5 Handling Course Enrollment
A possible workflow:
The student selects a course.
The backend validates course availability.
The payment provider processes payment.
The platform confirms the payment result.
The enrollment record is created.
An enrollment event is published.
A background worker sends a confirmation notification.
The platform should handle payment retries and delayed provider responses.
It should also define what happens when payment succeeds but enrollment creation fails. A recoverable workflow may use an outbox, retry process, or saga.
6 Scaling the Platform
As usage grows, the team can:
Add application instances.
Introduce a load balancer.
Cache frequently accessed course data.
Use a CDN for video and static assets.
Add read replicas where appropriate.
Move slow tasks to background workers.
Partition large tables when measurements justify it.
Separate high-load services when operational needs require it.
The team should measure bottlenecks before making major architectural changes.
7 Monitoring
Monitor:
API latency
API error rates
Database query duration
Database connection usage
Payment failures
Queue depth
Video delivery performance
Application resource usage
Use logs, metrics, and traces together to understand failures across components.
Common System Design Mistakes
Even a well-structured architecture can fail when teams make poor system design decisions.
1 Designing for Imaginary Scale
Some teams introduce distributed systems before they have evidence that the application needs them.
This creates extra deployment, monitoring, and communication complexity.
Start with the simplest design that satisfies the requirements. Keep clear boundaries so the system can evolve.
2 Choosing a Database Without Understanding Queries
A database should match the application's data model and access patterns.
Before selecting one, identify:
Important queries
Read/write ratio
Transaction requirements
Data relationships
Consistency expectations
Growth rate
3 Ignoring Failure Scenarios
A design that assumes every dependency is always available is incomplete.
Plan for:
Timeouts
Duplicate requests
Delayed messages
Database outages
Third-party API failures
Partial deployments
Recovery after interrupted workflows
4 Adding Caching Without an Invalidation Plan
Caching can improve performance, but stale data can create correctness problems.
Define expiration and invalidation rules before introducing a cache.
5 Ignoring Observability
Without useful logs, metrics, and traces, teams may struggle to identify production problems.
Observability should be part of the system design, not an afterthought.
6 Optimizing Without Measurements
Premature optimization can increase code complexity without improving actual performance.
Measure first. Identify the bottleneck. Make a targeted change. Measure again.
System Design Review Checklist
Use this checklist before approving a system design.
Requirements
Are functional requirements documented?
Are non-functional requirements measurable?
Are peak workloads estimated?
Are system boundaries clear?
APIs
Are endpoint names and behaviors consistent?
Are authentication and authorization defined?
Are errors predictable?
Are pagination and rate limits considered?
Are retry and idempotency rules documented?
Is API versioning planned?
Databases
Does the data model match application requirements?
Are relationships and constraints clear?
Are indexes based on real query patterns?
Are transaction boundaries defined?
Are backups and recovery tested?
Are replication and partitioning actually necessary?
Distributed Systems
Are network timeouts configured?
Are retries limited and controlled?
Are duplicate messages handled?
Are service dependencies documented?
Are partial failures considered?
Are long-running workflows recoverable?
Scalability
Can application instances scale horizontally?
Are shared resources monitored?
Are database limits understood?
Are background jobs controlled?
Is capacity planning based on realistic traffic?
Performance
Are latency and throughput measured?
Are slow queries reviewed?
Are load tests realistic?
Are resource limits configured?
Are performance objectives documented?
Operations
Are logs, metrics, and traces available?
Are alerts connected to meaningful service objectives?
Are deployment and rollback procedures defined?
Are recovery procedures tested?
Conclusion
System design connects architectural ideas with the practical needs of a working application.
Good API contracts help components communicate. Suitable database models protect data and support efficient queries. Distributed systems techniques help services coordinate despite network delays and partial failures. Caching and scaling strategies help applications handle increasing demand. Performance engineering ensures that improvements come from measurement rather than guesswork.
The most important lesson is to make decisions based on requirements and evidence.
A small application may work best with a modular monolith and a relational database. A larger platform may need independent services, event streaming, distributed storage, and advanced scaling strategies.
Neither approach is automatically correct. The best design is the one that meets the system's needs while remaining understandable, testable, secure, and maintainable.
Next: Part 4 – Security, Reliability, Testing, Deployment, DevOps, and Operations Engineering.
References and Further Reading
REST Architectural Style – Roy Fielding's dissertation: https://ics.uci.edu/~fielding/pubs/dissertation/top.htm
GraphQL Documentation – https://graphql.org/learn/
gRPC Documentation – https://grpc.io/docs/
PostgreSQL Documentation – https://www.postgresql.org/docs/
MySQL Documentation – https://dev.mysql.com/doc/
Redis Documentation – https://redis.io/docs/
Apache Kafka Documentation – https://kafka.apache.org/documentation/
Google SRE Books – https://sre.google/books/
AWS Well-Architected Framework – https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html
Microsoft Azure Architecture Center – https://learn.microsoft.com/azure/architecture/
Google Cloud Architecture Framework – https://cloud.google.com/architecture/framework
OpenTelemetry Documentation – https://opentelemetry.io/docs/
Disclaimer: This article is for educational purposes. Architecture choices should be tested against the requirements, security needs, workload, and operating conditions of each project.







No comments:
Post a Comment