Architecture Interview Questions - Easy

Easy-level software architecture interview questions covering fundamental patterns, principles, and concepts.

Q1: Explain the difference between monolithic and microservices architecture.

Answer:

Monolithic Architecture

Definition: Single unified application where all components are tightly coupled and deployed together.

Structure:

graph TB
    A[Monolithic Application]
    A --> B[UI Layer]
    A --> C[Business Logic]
    A --> D[Data Access Layer]
    D --> E[(Single Database)]
    
    style A fill:#FFD700

Pros:

  • Simple to develop and deploy
  • Easy to test (single codebase)
  • Better performance (no network calls between components)
  • Simpler debugging

Cons:

  • Hard to scale (must scale entire app)
  • Tight coupling (changes affect everything)
  • Long deployment times
  • Technology lock-in

Microservices Architecture

Definition: Application composed of small, independent services that communicate via APIs.

Structure:

graph TB
    A[API Gateway]
    A --> B[Service A]
    A --> C[Service B]
    A --> D[Service C]
    
    B --> E[(DB-A)]
    C --> F[(DB-B)]
    D --> G[(DB-C)]
    
    style A fill:#FFD700

Pros:

  • Independent scaling
  • Technology diversity
  • Faster deployments
  • Better fault isolation
  • Team autonomy

Cons:

  • Complex infrastructure
  • Network latency
  • Data consistency challenges
  • Harder to debug
  • Operational overhead

When to Use Each:

  • Monolith: Small teams, simple apps, MVPs, startups
  • Microservices: Large teams, complex domains, need to scale independently

Q2: What are the SOLID principles?

Answer:

S - Single Responsibility Principle (SRP)

Definition: A class should have only one reason to change.

Example:

 1❌ Bad:
 2class User {
 3    saveToDatabase()
 4    sendEmail()
 5    generateReport()
 6}
 7
 8✅ Good:
 9class User { ... }
10class UserRepository { saveToDatabase() }
11class EmailService { sendEmail() }
12class ReportGenerator { generateReport() }

O - Open/Closed Principle (OCP)

Definition: Open for extension, closed for modification.

Example:

 1❌ Bad:
 2class PaymentProcessor {
 3    process(type) {
 4        if (type == "credit") { ... }
 5        else if (type == "paypal") { ... }
 6        // Adding new type requires modifying this class
 7    }
 8}
 9
10✅ Good:
11interface PaymentMethod { process() }
12class CreditCard implements PaymentMethod { ... }
13class PayPal implements PaymentMethod { ... }
14// Add new payment methods without changing existing code

L - Liskov Substitution Principle (LSP)

Definition: Subtypes must be substitutable for their base types.

Example:

 1 Bad:
 2class Bird { fly() }
 3class Penguin extends Bird {
 4    fly() { throw Error("Can't fly!") }
 5}
 6
 7 Good:
 8class Bird { ... }
 9class FlyingBird extends Bird { fly() }
10class Penguin extends Bird { swim() }

I - Interface Segregation Principle (ISP)

Definition: Clients shouldn't depend on interfaces they don't use.

Example:

 1❌ Bad:
 2interface Worker {
 3    work()
 4    eat()
 5    sleep()
 6}
 7class Robot implements Worker {
 8    eat() { /* robots don't eat! */ }
 9}
10
11✅ Good:
12interface Workable { work() }
13interface Eatable { eat() }
14interface Sleepable { sleep() }
15class Human implements Workable, Eatable, Sleepable
16class Robot implements Workable

D - Dependency Inversion Principle (DIP)

Definition: Depend on abstractions, not concretions.

Example:

 1 Bad:
 2class EmailService { send() }
 3class Notification {
 4    emailService = new EmailService()  // Tight coupling
 5}
 6
 7 Good:
 8interface MessageService { send() }
 9class EmailService implements MessageService { ... }
10class SMSService implements MessageService { ... }
11class Notification {
12    constructor(messageService: MessageService) { ... }
13}

Benefits: Maintainable, testable, flexible, scalable code.


Q3: Explain the MVC (Model-View-Controller) pattern.

Answer:

Definition: Architectural pattern separating application into three interconnected components.

Components:

graph TB
    U[User] -->|interacts| C[Controller]
    C -->|updates| M[Model]
    C -->|selects| V[View]
    M -->|notifies| V
    
    M2[Model<br/>- Data<br/>- Logic]
    V2[View<br/>- UI<br/>- Display]
    C2[Controller<br/>- Handles input<br/>- Updates Model<br/>- Selects View]
    
    style C fill:#FFD700

Model

  • Responsibility: Data and business logic
  • Examples: User class, database queries, validation
  • Independent: Doesn't know about View or Controller

View

  • Responsibility: Presentation and UI
  • Examples: HTML templates, React components, mobile screens
  • Observes: Model for changes

Controller

  • Responsibility: Handle user input, coordinate Model and View
  • Examples: Route handlers, event handlers
  • Mediator: Between user and application

Flow:

  1. User interacts with View (clicks button)
  2. Controller receives input
  3. Controller updates Model
  4. Model notifies View of changes
  5. View updates display

Benefits:

  • Separation of concerns
  • Parallel development
  • Easier testing
  • Code reusability

Example Scenario (E-commerce):

  • Model: Product, Cart, Order classes with database logic
  • View: Product listing page, shopping cart UI
  • Controller: AddToCartController, CheckoutController

Variations:

  • MVP (Model-View-Presenter): Presenter mediates all View-Model interaction
  • MVVM (Model-View-ViewModel): Two-way data binding between View and ViewModel

Q4: What is RESTful API design?

Answer:

Definition: Architectural style for designing networked applications using HTTP methods and resources.

Core Principles:

1. Resource-Based

Everything is a resource with a unique URI:

1/users          - Collection of users
2/users/123      - Specific user
3/users/123/posts - User's posts

2. HTTP Methods (CRUD)

1GET    /users       - Retrieve all users
2GET    /users/123   - Retrieve user 123
3POST   /users       - Create new user
4PUT    /users/123   - Update user 123 (full)
5PATCH  /users/123   - Update user 123 (partial)
6DELETE /users/123   - Delete user 123

3. Stateless

Each request contains all information needed (no server-side session).

4. HTTP Status Codes

1200 OK                  - Success
2201 Created             - Resource created
3204 No Content          - Success, no response body
4400 Bad Request         - Invalid input
5401 Unauthorized        - Authentication required
6403 Forbidden           - No permission
7404 Not Found           - Resource doesn't exist
8500 Internal Server Error - Server error

5. Representation

Resources can have multiple representations (JSON, XML):

1GET /users/123
2Accept: application/json
3
4{
5  "id": 123,
6  "name": "Alice",
7  "email": "alice@example.com"
8}

Best Practices:

  1. Use nouns, not verbs:

    • GET /users
    • GET /getUsers
  2. Use plural names:

    • /users/123
    • /user/123
  3. Nested resources:

    • /users/123/posts/456
    • /posts/456 (if context matters)
  4. Filtering, sorting, pagination:

    1GET /users?role=admin&sort=name&page=2&limit=20
    
  5. Versioning:

    1/api/v1/users
    2/api/v2/users
    
  6. HATEOAS (Hypermedia):

    1{
    2  "id": 123,
    3  "name": "Alice",
    4  "_links": {
    5    "self": "/users/123",
    6    "posts": "/users/123/posts"
    7  }
    8}
    

Q5: Explain the difference between SQL and NoSQL databases.

Answer:

SQL (Relational) Databases

Structure: Tables with fixed schema, rows and columns

Examples: PostgreSQL, MySQL, Oracle, SQL Server

Schema:

erDiagram
    USERS {
        int id PK
        string name
        string email
        int age
    }

Example Data:

idnameemailage
1Alicealice@example.com30
2Bobbob@example.com25

Characteristics:

  • ACID transactions (Atomicity, Consistency, Isolation, Durability)
  • Structured data with relationships
  • Schema-first: Define structure before inserting data
  • Joins: Combine data from multiple tables
  • Vertical scaling: Add more CPU/RAM to single server

When to Use:

  • Complex queries and relationships
  • Transactions required (banking, e-commerce)
  • Data integrity critical
  • Structured, predictable data

NoSQL Databases

Types:

  1. Document (MongoDB, CouchDB):

    1{
    2  "_id": "123",
    3  "name": "Alice",
    4  "email": "alice@example.com",
    5  "addresses": [
    6    {"city": "NYC", "zip": "10001"},
    7    {"city": "LA", "zip": "90001"}
    8  ]
    9}
    
  2. Key-Value (Redis, DynamoDB):

    1user:123 → {"name": "Alice", "email": "..."}
    2session:abc → {"userId": 123, "expires": "..."}
    
  3. Column-Family (Cassandra, HBase):

    1Row Key: user:123
    2Columns: name=Alice, email=..., age=30
    
  4. Graph (Neo4j, ArangoDB):

    1(Alice)-[:FOLLOWS]->(Bob)
    2(Alice)-[:LIKES]->(Post1)
    

Characteristics:

  • Flexible schema: Add fields without migration
  • Horizontal scaling: Add more servers
  • Eventually consistent: May not be immediately consistent
  • Denormalized: Data duplication for performance

When to Use:

  • Massive scale (millions of users)
  • Flexible/evolving schema
  • Hierarchical data
  • High write throughput
  • Geographic distribution

Comparison

AspectSQLNoSQL
SchemaFixedFlexible
ScalingVerticalHorizontal
TransactionsACIDBASE (eventual consistency)
RelationshipsJoinsEmbedded/denormalized
Use CaseComplex queriesHigh scale, simple queries

Hybrid Approach: Many systems use both (SQL for transactions, NoSQL for caching/analytics).


Q6: What is the difference between authentication and authorization?

Answer:

Authentication (AuthN)

Question: "Who are you?"

Definition: Verifying identity of a user.

Methods:

  1. Password-based: Username + password
  2. Multi-factor (MFA): Password + SMS/app code
  3. Biometric: Fingerprint, face recognition
  4. Token-based: JWT, OAuth tokens
  5. Certificate-based: SSL/TLS client certificates

Flow:

1User → Provides credentials → System verifies → Issues token/session

Example:

 1POST /login
 2{
 3  "username": "alice",
 4  "password": "secret123"
 5}
 6
 7Response:
 8{
 9  "token": "eyJhbGciOiJIUzI1NiIs...",
10  "user": {"id": 123, "name": "Alice"}
11}

Authorization (AuthZ)

Question: "What can you do?"

Definition: Determining what an authenticated user can access.

Models:

  1. Role-Based (RBAC):

    1User → Role → Permissions
    2Alice → Admin → [read, write, delete]
    3Bob → User → [read]
    
  2. Attribute-Based (ABAC):

    1IF user.department == "HR" AND resource.type == "employee_record"
    2THEN allow
    
  3. Access Control Lists (ACL):

    1Document123:
    2- Alice: read, write
    3- Bob: read
    4- Charlie: none
    

Flow:

1User (authenticated) → Requests resource → System checks permissions → Allow/Deny

Example:

1GET /admin/users
2Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
3
4If user has "admin" role → 200 OK
5If user doesn't have "admin" role → 403 Forbidden

Comparison

AspectAuthenticationAuthorization
QuestionWho are you?What can you do?
ProcessVerify identityCheck permissions
WhenFirst (login)Every request
ResultToken/sessionAllow/deny access
ExampleLogin with passwordAdmin can delete users

Together in Practice:

11. User logs in (Authentication)
2   → System verifies credentials
3   → Issues JWT token with user info and roles
4
52. User requests resource (Authorization)
6   → System validates token (re-authentication)
7   → Checks user's roles/permissions
8   → Allows or denies access

Q7: What is caching and what are common caching strategies?

Answer:

Definition: Storing frequently accessed data in fast storage to reduce latency and load.

Cache Hierarchy:

graph TB
    A[Browser Cache<br/>fastest, smallest]
    B[CDN Cache]
    C[Application Cache<br/>Redis, Memcached]
    D[Database Query Cache]
    E[(Database<br/>slowest, largest)]
    
    A --> B --> C --> D --> E
    
    style A fill:#90EE90
    style E fill:#FFB6C1

Caching Strategies

1. Cache-Aside (Lazy Loading)

Flow:

11. Check cache
22. If miss → Read from DB → Store in cache
33. If hit → Return from cache

Pros: Only cache what's needed
Cons: Cache miss penalty, stale data possible

Use: General-purpose caching

2. Write-Through

Flow:

11. Write to cache
22. Immediately write to database
33. Return success

Pros: Cache always consistent
Cons: Write latency (two writes)

Use: Data consistency critical

3. Write-Behind (Write-Back)

Flow:

11. Write to cache
22. Return success immediately
33. Asynchronously write to database later

Pros: Fast writes
Cons: Risk of data loss

Use: High write throughput needed

4. Read-Through

Flow:

11. Check cache
22. If miss  Cache loads from DB automatically
33. Return data

Pros: Simplified application code
Cons: Cache must implement loading logic

5. Refresh-Ahead

Flow:

11. Predict which data will be needed
22. Refresh cache before expiration
33. Always serve from cache

Pros: No cache miss penalty
Cons: May refresh unused data

Use: Predictable access patterns

Cache Eviction Policies

LRU (Least Recently Used): Remove oldest accessed
LFU (Least Frequently Used): Remove least accessed
FIFO (First In First Out): Remove oldest added
TTL (Time To Live): Remove after expiration

Cache Invalidation

Problem: "There are only two hard things in Computer Science: cache invalidation and naming things."

Strategies:

  1. TTL-based: Expire after time
  2. Event-based: Invalidate on updates
  3. Version-based: Include version in cache key

Example:

 1# TTL-based
 2cache.set("user:123", data, ttl=3600)  # 1 hour
 3
 4# Event-based
 5onUserUpdate(userId) {
 6    cache.delete(`user:${userId}`)
 7}
 8
 9# Version-based
10cache.set(`user:123:v2`, data)

Q8: Explain the CAP theorem.

Answer:

Definition: In a distributed system, you can only guarantee 2 out of 3 properties:

C - Consistency

Definition: All nodes see the same data at the same time.

Example: After writing to any node, all subsequent reads return that value.

A - Availability

Definition: Every request receives a response (success or failure).

Example: System responds even if some nodes are down.

P - Partition Tolerance

Definition: System continues operating despite network partitions.

Example: System works even when nodes can't communicate.

Trade-offs

graph TB
    A[CAP Theorem]
    A --> B[CA<br/>Consistency + Availability<br/>Single-node RDBMS]
    A --> C[CP<br/>Consistency + Partition Tolerance<br/>MongoDB, HBase]
    A --> D[AP<br/>Availability + Partition Tolerance<br/>Cassandra, DynamoDB]
    
    style A fill:#FFD700
    style B fill:#87CEEB
    style C fill:#98FB98
    style D fill:#FFB6C1

CA (Consistency + Availability):

  • Single-node systems (no partitions possible)
  • Traditional RDBMS on single server
  • Example: PostgreSQL on one machine

CP (Consistency + Partition Tolerance):

  • Sacrifice availability during partitions
  • Wait for consensus before responding
  • Examples: MongoDB, HBase, Redis (with replication)

AP (Availability + Partition Tolerance):

  • Sacrifice consistency (eventual consistency)
  • Always respond, even with stale data
  • Examples: Cassandra, DynamoDB, CouchDB

Real-World Example

Banking System (CP):

1During network partition:
2- Can't guarantee all nodes have same balance
3- Better to reject transactions (unavailable)
4- Than allow inconsistent balances

Social Media Feed (AP):

1During network partition:
2- Better to show slightly stale feed
3- Than show error message
4- Eventual consistency acceptable

Note: In practice, partition tolerance is required (networks fail), so real choice is between CP and AP.


Q9: What are design patterns? Name common ones.

Answer:

Definition: Reusable solutions to common software design problems.

Creational Patterns (Object Creation)

1. Singleton: Ensure only one instance exists

 1class Database {
 2    private static instance;
 3    
 4    private constructor() {}
 5    
 6    static getInstance() {
 7        if (!instance) {
 8            instance = new Database();
 9        }
10        return instance;
11    }
12}

2. Factory: Create objects without specifying exact class

1class ShapeFactory {
2    createShape(type) {
3        if (type === "circle") return new Circle();
4        if (type === "square") return new Square();
5    }
6}

3. Builder: Construct complex objects step by step

1new UserBuilder()
2    .setName("Alice")
3    .setEmail("alice@example.com")
4    .setAge(30)
5    .build();

Structural Patterns (Object Composition)

4. Adapter: Make incompatible interfaces work together

1class PayPalAdapter implements PaymentProcessor {
2    constructor(paypal) { this.paypal = paypal; }
3    
4    processPayment(amount) {
5        this.paypal.sendMoney(amount);  // Adapt interface
6    }
7}

5. Decorator: Add behavior without modifying class

1class LoggingDecorator {
2    constructor(service) { this.service = service; }
3    
4    execute() {
5        console.log("Starting...");
6        this.service.execute();
7        console.log("Done");
8    }
9}

6. Proxy: Control access to object

 1class CachedAPI {
 2    constructor(api) {
 3        this.api = api;
 4        this.cache = {};
 5    }
 6    
 7    fetch(url) {
 8        if (this.cache[url]) return this.cache[url];
 9        this.cache[url] = this.api.fetch(url);
10        return this.cache[url];
11    }
12}

Behavioral Patterns (Object Interaction)

7. Observer: Notify multiple objects of changes

1class EventEmitter {
2    listeners = [];
3    
4    subscribe(listener) { this.listeners.push(listener); }
5    
6    notify(event) {
7        this.listeners.forEach(l => l.update(event));
8    }
9}

8. Strategy: Select algorithm at runtime

1class PaymentProcessor {
2    constructor(strategy) { this.strategy = strategy; }
3    
4    process(amount) {
5        this.strategy.pay(amount);
6    }
7}
8
9// Use: new PaymentProcessor(new CreditCardStrategy())

9. Command: Encapsulate requests as objects

1class SaveCommand {
2    constructor(document) { this.doc = document; }
3    execute() { this.doc.save(); }
4    undo() { this.doc.revert(); }
5}

10. Template Method: Define algorithm skeleton, let subclasses override steps

1class DataProcessor {
2    process() {
3        this.readData();
4        this.processData();  // Override in subclass
5        this.saveData();
6    }
7}

Q10: What is the difference between horizontal and vertical scaling?

Answer:

Vertical Scaling (Scale Up)

Definition: Add more resources (CPU, RAM, disk) to existing machine.

graph LR
    A[Before<br/>4 CPU<br/>8 GB RAM] -->|Scale Up| B[After<br/>16 CPU<br/>64 GB RAM]
    
    style A fill:#FFB6C1
    style B fill:#90EE90

Pros:

  • Simple (no code changes)
  • No distributed system complexity
  • Consistent data (single database)
  • Lower latency (no network calls)

Cons:

  • Hardware limits (can't scale infinitely)
  • Expensive (high-end hardware costs more)
  • Single point of failure
  • Downtime during upgrades

When to Use:

  • Small to medium applications
  • Monolithic architecture
  • Relational databases (PostgreSQL, MySQL)
  • When simplicity is priority

Horizontal Scaling (Scale Out)

Definition: Add more machines to distribute load.

graph TB
    A[Load Balancer]
    A --> B[Server 1]
    A --> C[Server 2]
    A --> D[Server 3]
    
    E[Before: Single Server] -.->|Scale Out| A
    
    style A fill:#FFD700
    style E fill:#FFB6C1

Pros:

  • Nearly unlimited scaling
  • Better fault tolerance (redundancy)
  • Cost-effective (commodity hardware)
  • No downtime (add servers without stopping)

Cons:

  • Complex (distributed systems)
  • Data consistency challenges
  • Network latency
  • Requires load balancing

When to Use:

  • Large-scale applications
  • Microservices
  • NoSQL databases (Cassandra, MongoDB)
  • High availability required

Comparison

AspectVerticalHorizontal
CostExpensiveCost-effective
LimitHardware limitNearly unlimited
ComplexitySimpleComplex
DowntimeYesNo
Fault ToleranceSingle point of failureRedundant
Data ConsistencyEasyChallenging

Hybrid Approach

Most systems use both:

graph TB
    A[Load Balancer]
    A --> B[Server 1<br/>16 CPU, 64 GB]
    A --> C[Server 2<br/>16 CPU, 64 GB]
    A --> D[Server 3<br/>16 CPU, 64 GB]
    
    style A fill:#FFD700
    style B fill:#90EE90
    style C fill:#90EE90
    style D fill:#90EE90

Strategy: Scale vertically until cost-prohibitive, then scale horizontally.


Summary

Key architecture concepts:

  • Architectural styles: Monolithic vs. Microservices
  • Design principles: SOLID
  • Patterns: MVC, design patterns
  • APIs: REST principles
  • Databases: SQL vs. NoSQL
  • Security: Authentication vs. Authorization
  • Performance: Caching strategies
  • Distributed systems: CAP theorem
  • Scaling: Vertical vs. Horizontal

These fundamentals form the foundation for more advanced architectural decisions.

Related Snippets