Web & Application Security

Chapter 7
Secure Architecture and Design Patterns

Advance Diploma in Cybersecurity
Web & Application Security   •   Advance Diploma

Secure Architecture and Design Patterns

Introduction

Web and application security is not achieved by adding a firewall or scanning code at the end of development. It is an architectural property: security requirements must influence trust relationships, data flows, deployment boundaries, failure behaviour, and operational controls from the beginning. A secure architecture reduces the likelihood and impact of compromise while preserving availability, usability, maintainability, and business value.

Modern applications commonly combine browsers and mobile clients, APIs, identity providers, containers, managed databases, event brokers, serverless functions, and third-party services. This distribution creates more interfaces and trust relationships than a traditional monolithic application. The architect must therefore ask not only “Can this component be attacked?” but also “What can an attacker do after reaching it, and how far can the compromise spread?”

This chapter presents practical patterns for layered, microservice, serverless, and cloud-native systems. It emphasises trust boundaries, gateways, web application firewalls (WAFs), service meshes, isolation, secure defaults, resilience, privacy by design, security requirements, and architecture decision records.

Learning Objectives

By the end of this chapter, a learner should be able to:

  1. Explain defence in depth, least privilege, zero trust, secure defaults, and fail-safe design.
  2. Identify trust boundaries and security-relevant data flows.
  3. Design layered, microservice, serverless, and cloud-native architectures with appropriate controls.
  4. Distinguish the roles of reverse proxies, API gateways, WAFs, identity providers, and service meshes.
  5. Apply isolation, resilience, privacy, and supply-chain controls to application designs.
  6. Document security requirements and architecture decisions in a reviewable form.
  7. Critically evaluate the limitations and operational costs of common security patterns.

1. Architectural Security Foundations

1.1 Defence in depth

Defence in depth uses multiple partially independent controls. For example, an internet-facing API may be protected by network filtering, TLS, a WAF, gateway authentication, service authorisation, input validation, database permissions, logging, and backup recovery. No single control is assumed to be perfect.

Controls should be complementary rather than duplicated. A WAF may detect a known injection pattern, but it should not replace parameterised queries. Encryption may protect confidentiality in transit, but it does not decide whether an authenticated user is authorised to view a record.

1.2 Least privilege and complete mediation

Least privilege grants a subject only the permissions required for its task, for only as long as required. Subjects include users, services, functions, administrators, build pipelines, and workload identities. Complete mediation means that every access to a protected resource is checked; a decision made once at login must not automatically be trusted for all subsequent operations.

A practical authorisation decision can be viewed as a function:

Permit = f(subject, action, resource, context, policy)

Here, subject is the requesting identity, action is the operation, resource is the target, context includes relevant conditions such as device, time, or network, and policy defines permitted relationships. The expression is conceptual rather than a universal implementation formula. Its purpose is to discourage decisions based only on a username or network location.

1.3 Secure defaults and fail-safe behaviour

A secure system should begin in a restrictive state. Examples include denying unauthenticated requests, disabling unused endpoints, encrypting storage by default, rejecting unknown fields, and requiring explicit permission for administrative functions. Configuration should not become less secure merely because an optional security setting was omitted.

Fail-safe behaviour must be chosen according to the asset and hazard. A payment authorisation service may fail closed when identity verification is unavailable. A public status page may fail open for availability of non-sensitive information. “Fail securely” is therefore a design decision, not a universal instruction.

1.4 Zero trust as an architectural stance

Zero trust does not mean that every request is treated as malicious with equal probability. It means that trust is not granted solely because a request originates inside a network. Identity, device or workload posture, resource, action, and context are evaluated explicitly, and access is continuously monitored. Network segmentation remains useful, but an internal subnet is not a sufficient authorisation boundary.

2. Trust Boundaries and Threat-Informed Design

A trust boundary is a point where data, authority, or assumptions change. Common boundaries occur between a browser and an API, an API gateway and a service, one service and another, an application and a database, a cloud account and a managed service, or a company and a supplier.

For each boundary, document:

  • the communicating parties and their identities;
  • the data crossing the boundary and its classification;
  • authentication, authorisation, confidentiality, and integrity requirements;
  • validation and canonicalisation responsibilities;
  • rate, size, and resource limits;
  • logging and monitoring requirements;
  • expected failure and retry behaviour.

Data-flow diagrams and threat modelling methods such as STRIDE help reveal threats. Spoofing concerns identity, tampering concerns integrity, repudiation concerns accountability, information disclosure concerns confidentiality, denial of service concerns availability, and elevation of privilege concerns unauthorised authority. Threat modelling is most effective when repeated at major design changes rather than performed once as paperwork.

Layered application architecture and trust boundaries ClientBrowser / mobile EdgeTLS, WAF, gateway ServicesBusiness logic DataDB, queue, object store Trust boundaryTrust boundaryTrust boundary Cross-cutting controlsIdentity • policy • secrets • telemetry • vulnerability management • recovery Security controls must be applied at every boundary
Layered application architecture showing trust boundaries and security controls
Figure: Layered application architecture showing trust boundaries and security controls

Figure: A layered architecture in which each transition is treated as a trust boundary.

3. Layered and Perimeter-Controlled Architectures

A conventional layered architecture separates presentation, application, domain, and data layers. The presentation layer handles interaction; the application layer coordinates use cases; the domain layer applies business rules; and the data layer manages persistence. The design is secure only when each layer enforces its own responsibilities.

The edge commonly contains a reverse proxy or API gateway. A reverse proxy forwards requests and can terminate TLS, hide internal topology, apply routing, and enforce connection limits. An API gateway adds API-oriented features such as authentication integration, quota management, schema validation, version routing, and usage analytics. A WAF analyses HTTP traffic for attack indicators such as suspicious injection or protocol violations. It is a filtering control, not proof that an application is safe.

A secure request path commonly includes:

  1. TLS protection and certificate validation.
  2. Request-size, method, content-type, and protocol checks.
  3. WAF inspection, with carefully tested rules.
  4. Authentication and token validation.
  5. Gateway-level quotas and abuse controls.
  6. Service-level authorisation and business-rule validation.
  7. Parameterised database access and constrained output.
  8. Security logging without exposing secrets or unnecessary personal data.

The gateway should not become a “god component” containing all business logic. Excessive centralisation creates a bottleneck, a high-value target, and a difficult deployment dependency. Conversely, allowing every service to implement unrelated authentication and rate-limiting logic creates inconsistency. Responsibilities should be explicit and tested.

4. Microservice Security Patterns

Microservices divide an application into independently deployable services, usually aligned with business capabilities. They can improve team autonomy and scaling, but they increase network calls, credentials, deployment artefacts, and failure modes.

4.1 Identity and service-to-service authorisation

Each service should have a distinct workload identity. Shared credentials undermine attribution and make rotation difficult. Mutual TLS (mTLS) can authenticate workloads and protect service traffic, while application-level authorisation determines whether the caller may perform a particular action. mTLS alone does not establish business permission.

A useful pattern is policy-based authorisation: the service presents its identity, requested action, resource, and relevant claims to a policy decision point. The protected service remains responsible for enforcing the result. Policies should be version-controlled, tested, and reviewed like code.

4.2 Service mesh

A service mesh provides infrastructure support for service-to-service communication, often through sidecar or node-level proxies. Typical capabilities include mTLS, traffic policy, retries, timeouts, circuit breaking, telemetry, and gradual traffic shifting. The mesh can standardise transport security, but it does not understand every business rule and can introduce operational complexity, latency, and new control-plane risks.

Retries require special care. Retrying a read may be safe; retrying a payment or account-creation operation may duplicate an action unless the operation is idempotent. An idempotency key allows a service to recognise repeated requests and return the original result rather than perform the operation again.

4.3 Data ownership and event security

A service should own its data and expose controlled interfaces rather than permit unrestricted cross-service database access. Events should be authenticated, authorised, schema-validated, ordered only where required, and protected against replay. Sensitive data in messages requires classification, retention limits, and access-controlled observability.

5. Serverless and Cloud-Native Design

Serverless functions reduce infrastructure administration by delegating runtime management to a cloud provider. They are commonly triggered by HTTP requests, queues, schedules, or storage events. Cloud-native systems also use containers, orchestration platforms, managed identity, infrastructure as code, and elastic services.

Security risks include over-permissive function roles, public storage, event injection, insecure dependencies, secrets in environment variables or code, unbounded concurrency, and excessive logging of personal data. Each function should have a narrow role, limited network access, explicit event validation, bounded execution time, and independent monitoring. Temporary execution environments must not be assumed to contain trustworthy state between invocations.

Container and orchestration controls include signed images, minimal base images, non-root execution, read-only filesystems where practical, admission policies, namespace or workload isolation, network policies, resource quotas, secret management, and regular patching. Infrastructure as code supports repeatability and review, but a secure template can still deploy an insecure public resource if its parameters are wrong. Policy-as-code can prevent prohibited configurations before deployment.

Cloud isolation is multi-dimensional: accounts or subscriptions, regions, virtual networks, subnets, security groups, workload identities, namespaces, and data stores provide different boundaries. A design should not confuse logical separation with cryptographic or physical separation when stronger isolation is required by risk or regulation.

6. Resilience as a Security Property

Availability is part of security. An attacker may exploit resource exhaustion, dependency failure, queue flooding, or cascading retries without stealing data. Resilient designs use bounded queues, timeouts, circuit breakers, bulkheads, back-pressure, graceful degradation, health checks, and tested recovery procedures.

A bulkhead isolates resources so that failure in one workload does not consume all threads, connections, memory, or worker capacity. Rate limiting should be applied at suitable dimensions: account, client, token, IP address, endpoint, and total system capacity. IP-only limits are weak against distributed attackers and may harm users behind shared networks.

Recovery objectives must be explicit. The recovery time objective (RTO) is the maximum acceptable time to restore service. The recovery point objective (RPO) is the maximum acceptable amount of data loss measured in time. These are business requirements, not properties automatically supplied by a cloud provider. Backups must be encrypted, access-controlled, monitored, and restored in exercises.

7. Privacy by Design

Privacy by design integrates privacy into architecture rather than treating it as a legal review after implementation. Core practices include data minimisation, purpose limitation, retention control, user transparency, access and correction mechanisms, pseudonymisation where appropriate, encryption, separation of identifiers, and privacy-preserving defaults.

Architects should distinguish confidentiality from privacy. Encryption may prevent unauthorised disclosure, but an organisation may still collect excessive data lawfully encrypted. Logs, traces, analytics, backups, and error reports are all potential copies of personal data. Sensitive values should be masked, tokenised, or excluded from telemetry, and retention should be technically enforced.

Applicable legal duties vary by jurisdiction and sector. Common governance concerns include lawful processing, data-subject rights, breach notification, cross-border transfers, records of processing, contractual supplier controls, and sector-specific retention obligations. Security architecture should support compliance but should not claim compliance merely because a control exists.

8. Security Requirements and Architecture Decisions

Security requirements translate risks and obligations into verifiable statements. A strong requirement identifies the asset, actor, condition, control, and acceptance test. For example: “The order API shall reject requests without a valid access token and shall return no order data unless the token’s subject is authorised for the specified account; automated tests shall demonstrate denial for an unauthorised account.”

Requirements may be functional, such as mandatory multi-factor authentication, or non-functional, such as a maximum recovery time. They should be prioritised according to risk and traced to tests, controls, and owners. Ambiguous statements such as “the system must be secure” are not testable.

An Architecture Decision Record (ADR) should contain:

ElementPurpose
ContextProblem, constraints, assumptions, and risks
DecisionChosen architecture and security controls
AlternativesOptions considered and reasons for rejection
ConsequencesBenefits, costs, residual risks, and operational effects
VerificationTests, monitoring, review date, and accountable owner

A decision may be expressed as: “Use a gateway for external API authentication and quota enforcement, while retaining object-level authorisation inside services.” The consequence is duplicated responsibility, but it prevents a compromised or misconfigured gateway from becoming the sole authorisation control.

Applied Case: Illustrative Online Health-Appointment Platform

Background

An illustrative health-appointment platform allows patients to search clinicians, book appointments, upload referral documents, and receive notifications. It uses a browser client, an API gateway, microservices, an object store, a relational database, a queue, and a serverless document-processing function.

Problem

The initial design placed the database on a broadly reachable network, used one shared service credential, logged full referral documents, and allowed the document function to access all storage buckets. A stolen credential could therefore expose patient records and enable lateral movement.

Analysis

The highest-risk trust boundaries are the public client-to-gateway boundary, gateway-to-service boundary, service-to-storage boundary, and event-to-function boundary. The referral document is highly sensitive. Availability is also important because missed appointments can cause harm, but emergency clinical decisions are not made by this platform.

Approach and solution

The revised architecture applies TLS at the edge and mTLS for selected internal service traffic. The gateway validates tokens, enforces request limits, and performs schema checks. Each service receives a separate workload identity. Object-level authorisation remains in the appointment service, which checks that the authenticated patient or authorised staff member may access a specific record.

The document function receives access only to a dedicated quarantine bucket and a narrow output location. It validates file type, size, and content before transferring a safe representation. The database is reachable only from required services through private network controls. Referral documents are encrypted, excluded from ordinary logs, and retained according to an approved schedule. Queue messages contain identifiers rather than full medical content where possible.

Timeouts, bounded retries, idempotency keys for bookings, queue limits, and circuit breakers reduce cascading failures. Backups are isolated from production credentials and restoration is tested. ADRs record why the gateway is not the sole authorisation point and why the document function is isolated.

Outcome

The revised design reduces blast radius, improves auditability, and supports privacy obligations. It also introduces costs: identity and policy management are more complex, service-to-service calls require observability, and document processing may be slower. These are accepted and monitored consequences rather than hidden assumptions.

Learning points

  1. A cloud service is not automatically a secure architecture.
  2. Identity separation limits lateral movement.
  3. Sensitive data must be controlled in logs and event payloads as well as databases.
  4. Security controls should be tied to explicit threats and acceptance tests.
  5. Resilience and privacy decisions must be documented alongside functional design.

Challenges and Limitations

Security patterns can fail through misconfiguration, untested assumptions, excessive complexity, or poor operational ownership. A WAF may generate false positives and false negatives. A service mesh may encrypt traffic while leaving authorisation incorrect. Microservices may multiply attack surface and make incident reconstruction harder. Serverless reduces infrastructure management but does not remove insecure code, vulnerable dependencies, or excessive permissions. Zero-trust programmes can become expensive identity projects if they lack clear risk priorities.

Security architecture must therefore include usability, performance, cost, accessibility, maintainability, and recovery. Controls should be measurable and periodically reassessed. Independent review, adversarial testing, secure code review, dependency analysis, configuration scanning, penetration testing, and incident exercises provide different evidence; none is sufficient alone.

Contemporary Developments and Professional Practice

Software supply-chain security increasingly includes dependency inventories such as software bills of materials, signed artefacts, provenance records, protected build systems, and controlled deployment identities. Confidential-computing technologies may protect data while in use in selected threat models, but they do not eliminate application-level authorisation risks.

Artificial intelligence can assist threat modelling, code review, anomaly detection, and policy analysis. However, generated recommendations may be incorrect, insecure, biased, or based on confidential inputs. Human review, reproducible tests, data governance, and approval controls remain necessary. AI components also require controls for prompt injection, data leakage, model supply-chain risks, and unsafe tool invocation when they can access application functions.

A professional architect should be able to explain not only which pattern was selected, but also its threat assumptions, failure modes, operational owner, evidence of effectiveness, and residual risk.

Best-Practice Checklist

  • Draw data flows and mark every trust boundary.
  • Classify data, including logs, backups, traces, and events.
  • Use distinct human and workload identities with least privilege.
  • Authenticate and authorise at the correct layer; do not rely on network location.
  • Use gateways and WAFs as complementary controls, not substitutes for secure code.
  • Isolate services, functions, tenants, environments, and sensitive data stores.
  • Validate schemas, sizes, content types, and canonical forms at boundaries.
  • Make retries bounded and operations idempotent where repetition is possible.
  • Apply secure defaults, deny-by-default policies, and tested recovery procedures.
  • Record significant decisions, alternatives, consequences, owners, and verification evidence.

Chapter Summary

Secure architecture places security requirements at the boundaries where identities, data, authority, and assumptions change. Defence in depth, least privilege, complete mediation, secure defaults, and zero-trust thinking provide foundational principles. Layered architectures use gateways, WAFs, validation, service authorisation, and protected data access, while microservice systems require distinct workload identities, controlled service communication, and disciplined data ownership. Service meshes can standardise transport security and resilience but cannot replace business authorisation.

Serverless and cloud-native platforms require narrow roles, isolated workloads, secure artefacts, policy-as-code, and careful event validation. Resilience controls such as timeouts, bulkheads, circuit breakers, bounded retries, and tested backups reduce security impact from exhaustion and dependency failure. Privacy by design limits collection, exposure, retention, and unnecessary replication. Finally, security requirements and ADRs make architectural reasoning testable, reviewable, and accountable.

Key Terms

Trust boundary: A point where data, identity, authority, or security assumptions change.

Defence in depth: Use of multiple complementary security controls.

Least privilege: Granting only the permissions necessary for an authorised task.

Complete mediation: Checking access whenever a protected resource is accessed.

Zero trust: An approach that avoids implicit trust based solely on network location.

API gateway: A managed entry point that routes and governs API traffic.

Reverse proxy: An intermediary that receives client requests and forwards them to internal servers.

WAF: A web application firewall that filters and analyses HTTP traffic.

Workload identity: An identity assigned to a service, function, container, or automated process.

mTLS: Mutual TLS, in which both communicating parties authenticate certificates.

Service mesh: Infrastructure for governing service-to-service communication and telemetry.

Bulkhead: Isolation of resources so one failure does not exhaust the whole system.

Circuit breaker: A mechanism that temporarily stops calls to a failing dependency.

Idempotency: A property in which repeating an operation has the same intended effect as performing it once.

RTO: Recovery time objective—the maximum acceptable restoration time.

RPO: Recovery point objective—the maximum acceptable time-based data loss.

Privacy by design: Integrating privacy protections into architecture and default operation.

ADR: Architecture Decision Record documenting context, decision, alternatives, and consequences.

Policy as code: Machine-enforceable policies managed through versioned development practices.

Blast radius: The extent of harm or affected resources after a compromise or failure.

Review Questions

Short Answer Questions

  1. What is a trust boundary, and why should it be marked on a data-flow diagram?
  2. Explain the difference between a WAF and an API gateway.
  3. Why does mTLS not by itself provide business authorisation?
  4. Define RTO and RPO.
  5. State two privacy risks associated with application logging.

Long Answer Questions

  1. Explain how defence in depth and least privilege work together in a layered web architecture.
  2. Compare the security benefits and limitations of microservices and a monolithic architecture.
  3. Describe a secure design for a serverless document-processing workflow.
  4. Explain how resilience mechanisms can prevent a dependency failure from becoming a security incident.
  5. Describe the contents and value of an Architecture Decision Record.

Analytical / Application Questions

  1. An internal service accepts requests from any workload in its private subnet. Analyse the trust assumptions, identify likely threats, and propose revised identity and authorisation controls.
  2. A payment service automatically retries every failed request three times. Evaluate the risks and design an approach using timeouts, bounded retries, and idempotency.
  3. Design trust boundaries and privacy controls for an application that stores customer profiles, uploaded documents, analytics events, and operational logs. Justify where data should be minimised, encrypted, masked, or retained.

Multiple Choice Questions with Answers

Question 1

Which control is primarily responsible for deciding whether an authenticated user may access a particular record?

A. Object-level authorisation in the service

B. TLS certificate renewal

C. Network address translation

D. Container image compression

Correct Answer: A. Object-level authorisation in the service

Question 2

What is the main architectural purpose of a WAF?

A. To replace database access controls

B. To analyse and filter web traffic for attack indicators

C. To provide business-process authorisation

D. To restore data after a ransomware attack

Correct Answer: B. To analyse and filter web traffic for attack indicators

Question 3

Why should microservices generally use distinct workload identities?

A. To eliminate the need for encryption

B. To allow every service unrestricted database access

C. To improve attribution and limit lateral movement

D. To ensure all services share one password

Correct Answer: C. To improve attribution and limit lateral movement

Question 4

Which statement best describes zero-trust architecture?

A. All internal network traffic is automatically trusted

B. Only internet users require authentication

C. Access is evaluated explicitly rather than trusted solely by network location

D. Security controls are unnecessary after a VPN is installed

Correct Answer: C. Access is evaluated explicitly rather than trusted solely by network location

Question 5

Which mechanism helps prevent a repeated booking request from creating duplicate bookings?

A. Idempotency key

B. Larger image size

C. DNS round-robin alone

D. Disabling audit logs

Correct Answer: A. Idempotency key

Question 6

What does a bulkhead pattern achieve?

A. It encrypts every database column automatically

B. It isolates resources so one failure does not exhaust the entire system

C. It removes the need for monitoring

D. It guarantees that a service never fails

Correct Answer: B. It isolates resources so one failure does not exhaust the entire system

Question 7

Which is an example of privacy by design?

A. Logging complete medical documents for convenience

B. Collecting every possible attribute before defining a purpose

C. Minimising data collection and enforcing retention limits

D. Making all backups publicly downloadable

Correct Answer: C. Minimising data collection and enforcing retention limits

Question 8

What is the primary purpose of an Architecture Decision Record?

A. To document context, choices, alternatives, and consequences

B. To store user passwords in plain text

C. To replace all security testing

D. To guarantee regulatory compliance automatically

Correct Answer: A. To document context, choices, alternatives, and consequences

Question 9

A function processes uploaded files. Which design best limits compromise impact?

A. Give it access to every storage bucket

B. Use a narrow role and separate quarantine and output locations

C. Disable file validation to improve performance

D. Place cloud credentials in source code

Correct Answer: B. Use a narrow role and separate quarantine and output locations

Question 10

Which statement about a service mesh is most accurate?

A. It can provide transport security and telemetry but does not replace business authorisation

B. It guarantees that application logic contains no vulnerabilities

C. It eliminates the need for workload identities

D. It makes all retries safe for payment operations

Correct Answer: A. It can provide transport security and telemetry but does not replace business authorisation

Web & Application Security
Chapter 7 of 14