ArchitectMind
  1. Home
  2. Tutorials
  3. Book 10 · Security, System Design & Solution Architecture
  4. Volume I
  5. Security Principles
Book 10 · Volume I — Security Architecture · Topic 1.3

Security Principles

Least privilege, defense in depth, fail secure, zero trust and secure by design

11 min readStage 4 · Production & architecture10 interview questions
Chapter
Chapter 1 — Security Architecture Fundamentals
Prerequisites
Topics 1.1–1.2
You will be able to
Apply each principle as concrete, testable design practices, combine them without contradiction, avoid fail-open behaviours, design independent control layers, and embed secure-by-design practices into delivery
Covers
Least privilege · Defense in depth · Fail secure · Zero trust · Secure by design
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts — The Five Principles
  4. 4. How It Works Internally — Least Privilege in Layers
  5. 4A. Deep Dive — Defense in Depth Done Right
  6. 4B. Deep Dive — Fail Secure
  7. 4C. Deep Dive — Zero Trust as a Principle
  8. 4D. Deep Dive — Secure by Design
  9. 4E. Deep Dive — Principle Conflicts and Balance
  10. 5. APIs / Features / Syntax
  11. 6. Practical Examples
  12. 7. Common Problems & Mistakes
  13. 8. Performance & Production Considerations
  14. 9. Architecture & Design Considerations
  15. 10. Interview Questions & Answers

1Concept / Definition

Security principles are design rules that guide every security decision regardless of technology. Five are central to modern architecture: least privilege (minimum access for minimum time), defense in depth (multiple independent control layers), fail secure (errors default to a safe state), zero trust (never trust implicitly; verify every request) and secure by design (security built in from the start through threat modeling and secure defaults).

Principles to practices
Figure 1 — Principles to practices
Defense in depth
Figure 2 — Defense in depth
VocabularyMeaning
Privilege creepAccumulation of unnecessary permissions over time
Common-mode failureOne flaw defeating multiple layers
Fail openAllowing access when a control fails
Secure defaultSafe configuration without extra effort
Table 1 — Terms

2Why It Exists

ViolationConsequence
Over-privileged service roleBreach escalates to all data
Single control layerOne bypass = full compromise
Fail-open authorizationOutage becomes breach
Implicit network trustLateral movement
Security bolted on lateExpensive redesigns
Table 2 — Why

3Core Concepts — The Five Principles

PrinciplePractices
Least privilegeScoped IAM roles per service; OAuth scopes; JIT admin; no standing prod access; periodic reviews; Access Analyzer
Defense in depthEdge (WAF) + network (segmentation) + identity (MFA) + app (authZ) + data (encryption) + monitoring
Fail secureDeny on authZ errors; closed circuit for security checks; generic error messages
Zero trustAuthenticate every request; mTLS; context-aware policies; micro-segmentation
Secure by designThreat models; secure templates; security in definition of done; memory-safe frameworks
Table 3 — Practices

4How It Works Internally — Least Privilege in Layers

LayerImplementation
HumanIdentity Center permission sets; JIT elevation 1 h; quarterly reviews
Service → AWSOne IAM role per service, resource-scoped ARNs, conditions
Service → serviceMesh AuthorizationPolicy by identity
TokenScopes and audience per API; short lifetimes
DataRow-level security; column masking for support roles
TimeTemporary credentials, expiring grants
Table 4 — Least privilege everywhere

4ADeep Dive — Defense in Depth Done Right

GuidelineDetail
Independent layersDifferent mechanisms, owners and failure modes
Avoid common-modeDon't rely on one IdP config for all layers
Detect when a layer failsMonitoring as a layer
Don't stack useless layersEach must reduce risk measurably
ExampleWAF blocks SQLi patterns, but code uses parameterised queries anyway
Table 5 — Layers that actually help

4BDeep Dive — Fail Secure

Fail open vs fail secure
Figure 3 — Fail open vs fail secure
SituationFail-secure behaviour
Authorization service unreachableDeny (with cached decisions for low-risk reads if policy allows)
Token validation error401, no partial access
Exception during permission checkDeny, log
Feature flag service downDefault to safe (feature off)
Crypto library errorAbort operation
Error messagesGeneric to user, detailed in secure logs
Table 6 — Default to deny

4CDeep Dive — Zero Trust as a Principle

TenetPractice
Verify explicitlyIdentity, device, context every time
Least privilegePer-request scopes, JIT
Assume breachSegment, encrypt, monitor, limit blast radius
Applied toUsers, workloads, networks, data (Chapter 5 details)
Table 7 — Zero trust in brief

4DDeep Dive — Secure by Design

PracticeDetail
Threat modeling in design phaseChapter 7
Secure defaults in templatesDeny-all security chains, TLS, encryption
Paved roadsPlatform modules with controls built in
Secure frameworksSpring Security, parameterised JPA, auto-escaping templates
Security requirements in storiesAcceptance criteria
Eliminate classes of bugsE.g. no native deserialization, no string-built SQL
TransparencySBOMs, vulnerability disclosure
Table 8 — Build it in

4EDeep Dive — Principle Conflicts and Balance

TensionResolution
Least privilege vs developer velocitySelf-service JIT, permission boundaries
Fail secure vs availabilitySeparate safety of decision from availability of service (degraded read-only)
Defense in depth vs complexityOnly layers with measurable value
Zero trust vs latencyEfficient mTLS, cached decisions
Table 9 — Practical balance

5APIs / Features / Syntax

JAVA
// Fail secure: any error in the authorization decision results in denial
public boolean canApprove(User user, Transfer transfer) {
    try {
        return pdp.isAllowed(user, "transfer:approve", transfer)
            && !transfer.createdBy().equals(user.id());  // separation of privilege
    } catch (Exception e) {
        log.atError().setCause(e).addKeyValue("transfer", transfer.id())
           .log("authorization decision failed - denying");
        return false;                                            // deny on error
    }
}
JSON
// Least privilege IAM for a service: one bucket prefix, one KMS key, TLS-only
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["s3:GetObject"],
    "Resource": "arn:aws:s3:::novabank-statements/customer-docs/*",
    "Condition": { "Bool": { "aws:SecureTransport": "true" } }
  }, {
    "Effect": "Allow",
    "Action": ["kms:Decrypt"],
    "Resource": "arn:aws:kms:ap-south-1:111122223333:key/statements-key-id"
  }]
}
YAML
# Secure by design: CI policy fails on wildcard IAM actions (Checkov custom check config)
metadata:
  id: CKV2_NB_1
  name: "No wildcard actions in IAM policies"
  category: IAM
definition:
  cond_type: attribute
  resource_types: [aws_iam_policy]
  attribute: policy.Statement[*].Action
  operator: not_contains
  value: "*"

6Practical Examples

6.1 Least privilege reduced breach impact

In a red-team exercise, a compromised statements service could read only its S3 prefix and decrypt with one key — no customer database access, no other buckets.

6.2 Fail-open bug fixed

A legacy entitlement check returned "allow" when the entitlement service timed out. Changing it to deny with a cached read-only fallback removed a critical risk.

6.3 Secure-by-design templates

ShopNow's service scaffold includes deny-all Spring Security, JWT validation, actuator lockdown, structured security logging and OWASP dependency checks — new services start secure.

6.4 Worked example — privilege review

FindingAction
Role unused permissions (Access Analyzer)Removed 38 actions
Table 10 — Fight privilege creep

6.5 Worked example — defense layers for SQLi

LayerControl
EdgeWAF SQLi rule
AppParameterised queries
DBLeast-privilege DB user
MonitorAnomaly alerts
Table 11 — Independent layers

6.6 Worked example — JIT access

RequestGrant
Prod DB read for incident1 hour, approved, recorded
Table 12 — Time-bound privilege

6.7 Worked example — interview whiteboard

PromptAnswer outline
"Which security principles guide your designs and how?""Least privilege (scoped roles, scopes, JIT, reviews), defense in depth (independent layers edge→data→monitoring, avoid common mode), fail secure (deny on errors, safe defaults, generic messages), zero trust (verify every request, mTLS, context, segmentation, assume breach), secure by design (threat models, secure defaults, paved roads, eliminating bug classes). Make each testable (CI checks, Config rules, tests) and balance with usability and availability."
Table 13 — Structured answer

6.8 Worked example — PayGrid scopes

ClientScopes
Merchant reporting apppayments:read only
Table 14 — Least privilege for tokens

6.9 Worked example — anti-patterns

Anti-patternEffect
Admin roles for convenienceLarge blast radius
Layers sharing one weaknessFalse sense of depth
catch (Exception) → allowFail open
Security review at the endLate, costly changes
Table 15 — Common mistakes

6.10 Worked example — NovaBank zero trust

ChangeDetail
VPN replaced by Verified AccessPer-app, device-aware access
Table 16 — Principle in action

6.11 Worked example — secure defaults

DefaultWhere
Encryption on, public access blockedLanding zone baseline
Table 17 — Default safe

6.12 Worked example — degraded mode

Dependency failureMode
Fraud service downLow-value transfers allowed with limits; high-value denied
Table 18 — Fail secure with business continuity

6.13 Worked example — error handling

ResponseContent
User"Unable to process request" + correlation ID
LogsFull detail
Table 19 — No leakage

6.14 Worked example — eliminating a bug class

ChangeEffect
Ban Java native deserialization via ArchUnit ruleRemoves gadget-chain risk
Table 20 — Systemic fix

6.15 Worked example — measuring principles

MetricTarget
Wildcard IAM policies0
Standing admin users0
Services with deny-all default100%
Table 21 — Testable principles

6.16 Worked example — interview follow-ups

Follow-upAnswer
"Fail secure vs availability?"Deny unsafe actions; design degraded modes for availability
"Is defense in depth just more tools?"No — independent, meaningful layers
Table 22 — Common probes

6.17 Worked example — checklist

Item✔
Least privilege enforced + reviewed✔
Independent layers✔
Fail-secure code paths✔
Zero-trust access✔
Secure-by-design templates✔
Metrics✔
Table 23 — Principles baseline

6.18 Worked example — separation of duties

ActionRule
Deploy to prodAuthor ≠ approver
Table 24 — Integrity of change

6.19 Worked example — least privilege for CI

PipelineRole
Service deployOnly its namespace/account
Table 25 — Supply chain containment

6.20 Worked example — secure by design pledge items

ItemShopNow
MFA for all staff✔
Default passwords eliminated✔
Vulnerability disclosure policy✔
Table 26 — Industry practices

6.21 Worked example — interview scenario

QuestionAnswer
"Developers complain least privilege slows them"Self-service JIT, permission boundaries, better templates
Table 27 — Balance with DX

6.22 Worked example — assume breach drill

DrillOutcome
Compromised pod simulationDetection in 4 min, containment in 7
Table 28 — Principle tested

6.23 Worked example — defaults in libraries

Library choiceBenefit
Thymeleaf auto-escapingXSS prevention by default
Table 29 — Secure frameworks

6.24 Worked example — privilege expiry

GrantExpiry
Vendor access30 days, renewable
Table 30 — Time-bound

6.25 Worked example — layered data protection

LayerControl
AccessIAM + app authZ
StorageKMS
UseMasking/tokenisation
Table 31 — Data depth

6.26 Worked example — principle review in ADRs

SectionQuestion
PrinciplesWhich principles does this design uphold or weaken?
Table 32 — Explicit reasoning

7Common Problems & Mistakes

MistakeFix
Over-privilegeScoping + reviews
Correlated layersIndependence
Fail openDeny on error
Late securitySecure by design
Table 33 — Mistakes and fixes

The most damaging mistakes are usually quiet ones. Privilege creep happens because access is granted for a project or incident and never removed, so a role that started with five actions ends up with eighty; without Access Analyzer reviews and expiring grants nobody notices until a breach shows the blast radius. Correlated layers are the second trap: a WAF, an API gateway and the service may all trust the same identity provider configuration, so one misconfigured issuer defeats all three. Fail-open code is often written innocently, as a catch block that returns true so that an outage does not block customers. Finally, principles stated in a policy document but never turned into CI checks or tests decay within a few releases.

8Performance & Production Considerations

ConsiderationPractice
Authorization latencyLocal/embedded PDPs
mTLS overheadConnection reuse
JIT frictionFast approvals
Table 34 — Operating principles

Principles have a runtime cost, so design them to be cheap on the hot path. Calling a remote policy decision point on every request adds a network hop and a new dependency; embedding the policy engine as a library or sidecar with locally distributed policies keeps authorization latency to well under a millisecond, and short-lived cached decisions can cover low-risk reads. Mutual TLS is inexpensive once connections are reused and certificates are rotated automatically by the mesh or ACM Private CA. Just-in-time access only works in production if approvals take minutes rather than days, otherwise engineers find workarounds. Track adherence as operational metrics, such as wildcard policies, standing admin users and fail-secure test coverage, and alert when they drift.

9Architecture & Design Considerations

GuidelineDetail
Principles → practices → checksTestable
Balance with usabilityAdoption
Revisit in ADRsExplicit
Table 35 — Design guidance

10Interview Questions & Answers

Q1BasicConcept

What is least privilege?

Least privilege means every identity, whether a person, service, pipeline or token, gets only the permissions it needs, on only the resources it needs, for only as long as it needs them. The goal is to limit blast radius: if a credential is stolen, the attacker can do very little with it. In practice that means one IAM role per service scoped to specific ARNs and conditions, OAuth scopes and audiences per API, database users that cannot run DDL, and no standing production admin access. Time matters as much as scope, so temporary credentials and just-in-time elevation that expires after an hour are part of the principle, not an extra.

Q2BasicConcept

What is defense in depth?

Defense in depth means protecting an asset with several independent layers of control, so that the failure or bypass of one layer does not lead straight to compromise. A typical stack runs from the edge, with a WAF and DDoS protection, through network segmentation, strong identity with MFA, application-level authorization and input validation, to data encryption and finally monitoring that detects when a layer has failed. The key word is independent: layers should use different mechanisms, owners and failure modes. A WAF rule against SQL injection is useful, but the code must still use parameterised queries and the database user must still lack rights to drop tables.

Q3IntermediateConcept

What does fail secure mean?

Fail secure means that when a security control or one of its dependencies fails, the system defaults to the safe state, which is usually to deny. If the authorization service is unreachable, a token cannot be validated, or an exception is thrown during a permission check, the request is refused rather than allowed through. Feature flags for risky capabilities default to off, and cryptographic errors abort the operation. Error messages to users stay generic, with a correlation ID, while the detail goes to secure logs so failures do not leak internals. The classic bug it prevents is a catch block that returns true, which turns an ordinary outage into a security breach.

Q4IntermediateConcept

What is zero trust?

Zero trust is the principle that no request is trusted because of where it comes from. Being inside the corporate network or the VPC grants nothing; every request from a user, device or workload is authenticated, authorized and evaluated against context such as device posture, location and risk. Its three tenets are verify explicitly, use least privilege per request, and assume breach, which drives segmentation, encryption everywhere and monitoring to limit lateral movement. In practice that looks like mTLS between services with mesh authorization policies, short-lived scoped tokens, and replacing broad VPN access with per-application access such as AWS Verified Access. It applies to users, workloads, networks and data alike.

Q5Senior EngineerConcept

What is secure by design?

Secure by design means security is built into a system from its first design decision rather than bolted on before go-live. It starts with threat modeling during design, so risks shape the architecture while changes are cheap. It continues with secure defaults that need no extra effort, such as a service template with deny-all Spring Security, TLS, encryption and locked-down actuator endpoints, and paved roads where the platform provides these controls ready-made. Mature teams also eliminate whole classes of bugs, for example banning native Java deserialization or string-built SQL with ArchUnit rules, and put security acceptance criteria in stories. CISA's Secure by Design pledge pushes vendors in the same direction.

Q6Senior EngineerDesign

How do you prevent privilege creep?

Privilege creep is prevented by making access expire and by measuring what is actually used. Grants for projects, incidents and vendors should be time-bound by default, through just-in-time elevation and expiring permission sets, so nothing accumulates silently. Unused-access analysis, such as IAM Access Analyzer's last-accessed data, shows which actions a role has never exercised, and those are removed; one review at NovaBank removed thirty-eight actions from a single role. Quarterly access reviews with named owners catch human accounts, and joiner, mover and leaver processes remove access when people change teams. Define roles in code, so every permission change goes through review and the policy history is auditable.

Q7Technical ArchitectTricky

What is a common-mode failure in defense in depth?

A common-mode failure is a single flaw that defeats several defensive layers at once because they share a mechanism, dependency or assumption. Defense in depth only works if layers fail independently. If the API gateway, the service and the admin console all validate tokens against one identity provider configuration, a mistake such as accepting an unsigned token or the wrong issuer breaks all three together. The same happens when several layers rely on one vendor library, one shared secret or one team's review. To avoid it, vary the mechanisms, separate ownership, keep controls such as database permissions that do not depend on the identity layer, and monitor each layer separately.

Q8Technical ArchitectTrade-off

How do you balance fail secure with availability?

Separate the safety of a decision from the availability of the service. Fail secure applies to the decision itself: if the control cannot reach a trustworthy answer, the risky action is denied. Availability is then protected by designing degraded modes in advance rather than by failing open. If the fraud service is down, low-value transfers can proceed within strict limits while high-value ones are refused or queued. If the policy engine is unreachable, cached decisions may allow low-risk reads for a short period. The business, risk and security owners should agree each degraded mode explicitly, document it in an ADR, and test it in game days so it behaves as intended.

Q9Solution ArchitectDesign

How do you make principles testable?

Turn each principle into concrete practices, and each practice into an automated check with a target. Least privilege becomes a CI policy, such as a Checkov rule, that fails the build on wildcard IAM actions, plus AWS Config rules for standing admin users. Fail secure becomes unit tests proving that an exception in the authorization path returns deny. Secure by design becomes ArchUnit rules banning native deserialization, and a template every new service must start from. Zero trust becomes mesh policies with default deny that are verified in tests. Then track the results as metrics on a dashboard, for example zero wildcard policies, zero standing admins and one hundred percent deny-all defaults.

Q10Solution ArchitectConcept

How do principles appear in documentation?

Principles appear in documentation mainly through architecture decision records. Every significant ADR should include a short section stating which security principles the design upholds or weakens and how any residual risk is handled. For example, an ADR introducing cached authorization decisions would note that it relaxes fail secure for low-risk reads, set a cache lifetime, and record who accepted the risk. Principles also belong in the architecture principles page with their measurable practices, in threat models linked from the design, and in service templates' documentation. Writing the reasoning down makes trade-offs reviewable by security and risk owners and stops individual developers making them silently in code.

Newsletter

Get new tutorials every week

New ArchitectMind tutorials and interview questions, once a week. No spam, unsubscribe anytime.

Almost done! Check your inbox and click the confirmation link to complete your subscription.
Keep going in Book 10

Security, System Design & Solution Architecture

Volume I · Topic 1.1

Security Architecture

Security Architecture

Volume I · Topic 1.2

CIA Triad

Security Architecture

Volume II · Topic 1.1

What Is System Design?

System Design Fundamentals

Volume II · Topic 1.2

Requirements

System Design Fundamentals

Volume II · Topic 1.3

Constraints

System Design Fundamentals

Volume III · Topic 1.1

Traffic Distribution

Large-Scale & Distributed System Design

Volume III · Topic 1.2

Load Balancing

Large-Scale & Distributed System Design

Volume III · Topic 1.3

Horizontal Scaling

Large-Scale & Distributed System Design

Volume IV · Topic 1.1

Understanding the Business

End-to-End Solution Architecture

Volume IV · Topic 1.2

Stakeholder Identification

End-to-End Solution Architecture

Volume IV · Topic 1.3

Business Capabilities

End-to-End Solution Architecture

Volume V · Topic 1.1

ADR

Architecture Decisions, Trade-offs & Risk

Volume V · Topic 1.2

Decision Context

Architecture Decisions, Trade-offs & Risk

Volume V · Topic 1.3

Alternatives

Architecture Decisions, Trade-offs & Risk

Volume VI · Topic 1.1

Legacy System Discovery

Legacy Modernization & Transformation

Volume VI · Topic 1.2

Dependency Analysis

Legacy Modernization & Transformation

Volume VI · Topic 1.3

Architecture Reverse Engineering

Legacy Modernization & Transformation

Volume VII · Topic 1.1

Architecture & Agile

Solution Architecture Delivery & Governance

Volume VII · Topic 1.2

Architecture & Product Management

Solution Architecture Delivery & Governance

Volume VII · Topic 1.3

Architecture & Development Teams

Solution Architecture Delivery & Governance

Volume VIII · Topic 1.1

Clarifying Requirements

Solution Architect Workshops, Interviews & Final Assessment

Volume VIII · Topic 1.2

Asking the Right Questions

Solution Architect Workshops, Interviews & Final Assessment

Volume VIII · Topic 1.3

Identifying Constraints

Solution Architect Workshops, Interviews & Final Assessment