Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 60

Designing Secure Systems: Auth, AuthZ, and Data Protection

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome to your next lesson in the Staff-Level System Design Depth module.

In our last lesson, we built a comprehensive observability strategy, focusing on how to understand the internal state of a complex distributed system to answer the question, "Is it working, and why isn't it?" We covered metrics, logs, and traces as the pillars for ensuring operational health.

Today, we shift from operational integrity to security. Once a system is observable, we must ensure it's also secure. The learning outcome for this lesson is to articulate a security model for a system design, covering authentication, authorization, and data protection.

For a Staff or Senior Staff engineer, discussing security goes far beyond simply saying "we'll use passwords." You're expected to demonstrate a deep understanding of the principles, architectural patterns, and trade-offs involved in securing a large-scale distributed system. This includes managing identities, controlling access at scale, and protecting sensitive data. Your ability to articulate a robust security model is a direct reflection of your sense of ownership and your capacity to manage risk.

We will structure our discussion around three core security pillars:

  1. Authentication: Verifying identity ("Who are you?").
  2. Authorization: Enforcing permissions ("What can you do?").
  3. Data Protection: Safeguarding data in transit and at rest.

1. The Core Principles: Authentication vs. Authorization

In any security discussion, it's critical to start with precise definitions. While they are often used together, authentication and authorization serve two distinct purposes.

How to Design Robust Authentication and Authorization in Microservices

To establish a clear foundation, let's start with this article from Medium that clearly distinguishes between these two fundamental concepts.

Please read the sections 'Understanding the Problem' and 'Differentiating Authentication and Authorization'. Focus on the core definitions and the simple example provided to solidify the distinction.

To summarize:

  • Authentication (AuthN) is the process of proving an identity. When you log in with a username and password, or when a service presents a security token, you are authenticating.
  • Authorization (AuthZ) is the process that happens after successful authentication. It determines what actions an authenticated identity is permitted to perform.

A simple analogy: Authentication is showing your ID to enter a building. Authorization is determining which floors your keycard gives you access to.


2. Authentication in Distributed Systems

In monolithic systems, authentication was often handled with server-side sessions. However, in a distributed microservices architecture, managing session state across dozens or hundreds of services becomes a major scalability bottleneck. The modern standard is stateless, token-based authentication.

To understand this shift, let's compare the two approaches and dive deep into the mechanics of JSON Web Tokens (JWTs).

Session Vs JWT: The Differences You May Not Know!

The video 'Session Vs JWT' from ByteByteGo provides an excellent, concise explanation of both session-based and JWT-based authentication flows, their trade-offs, and critical security considerations.

Please watch the entire video (it's about 6.5 minutes). Pay close attention to: The flow diagrams for both session and JWT authentication. The concept of statelessness with JWTs and why it's beneficial for microservices. The difference between symmetric (HMAC) and asymmetric (RSA/ECDSA) signing algorithms. The role of short-lived access tokens combined with long-lived refresh tokens.

Let's break down the key takeaways for an interview context.

Key Takeaways for Authentication:

  • Stateless is Scalable: JWTs are powerful because they are stateless. The user's identity and permissions (claims) are encoded within the token itself. A service can validate a token without calling back to a central authentication server or a shared session store, making the architecture highly scalable and performant.

  • API Gateway as the First Line of Defense: In a typical microservices architecture, an API Gateway acts as the single entry point. It's the ideal place to perform initial authentication. The gateway validates the incoming token and can then inject user identity information into downstream requests.

  • Signing Algorithm Trade-offs (Staff+ Topic):

    • Symmetric (HMAC): A single shared secret is used to both sign and verify the token. This is simpler and faster but requires every service that verifies tokens to have access to the secret. This increases the risk of the secret being compromised.
    • Asymmetric (RSA/ECDSA): A private key is used to sign the token, and a public key is used to verify it. The authentication service holds the private key securely. Other microservices only need the public key to validate tokens. This is a much more secure pattern for distributed systems as the private key is never shared. Discussing this trade-off shows depth.
  • Access Tokens + Refresh Tokens: Because JWTs cannot be easily revoked before they expire, a best practice is to issue short-lived access tokens (e.g., 15 minutes). When the access token expires, the client uses a separate, long-lived refresh token to obtain a new access token without forcing the user to log in again. The refresh token can be revoked on the server side if needed (e.g., if a user's session is compromised). This pattern balances security and user experience.


3. Authorization at Scale: From RBAC to Zanzibar

Once a user is authenticated, every service must authorize their requests. Simple models like Role-Based Access Control (RBAC) work well for many systems, but they can struggle with the complexity and scale of modern applications.

Microservices Security Architecture (+ Cybersecurity basics)

To frame our discussion on authorization, let's watch a segment of the 'Microservices Security Architecture' video. It introduces the role of tokens in carrying security context and touches upon foundational concepts.

Watch the section from 03:39 to 04:22. This part explains how the security context (like user roles and permissions) is passed between services using tokens and how individual services perform authorization checks.

Authorization Models:

  • Role-Based Access Control (RBAC): You define roles (admin, member, guest) and assign permissions to those roles. Users are then assigned to roles. It's simple and predictable.
  • Attribute-Based Access Control (ABAC): This is a more powerful and flexible model where access decisions are based on a combination of attributes of the user, the resource they are trying to access, and the environment. For example: Allow if user.role == 'editor' AND resource.owner == user.id.

While these models are sound, implementing them consistently, correctly, and performantly across a global, distributed system is a massive challenge. This leads to the "billion-dollar question" in distributed authorization: how do you solve this problem at Google's scale?

Case Study: Google Zanzibar

For your interviews, especially at Google, being able to discuss Zanzibar is a significant differentiator. It is Google's global authorization system that powers products like Google Drive, YouTube, and Calendar.

How Google Manages Trillions of Authorizations with Zanzibar

This article from ByteByteGo provides an excellent, high-level overview of Zanzibar's architecture and core concepts. Understanding this will equip you to discuss scalable authorization with authority.

Please read the sections 'The Core Problem: Authorization at Scale', 'The Data Model', and 'Handling Consistency with Ordering'. Focus on: The 'new enemy' problem and why consistency is so hard. The (object, relation, user) tuple data model. How 'zookies' are used to ensure that permission checks are not stale.

Here are the key concepts from Zanzibar to highlight in an interview:

  1. Flexible Data Model: Zanzibar models all permissions as relation tuples: object#relation@user.

    • Example: doc:budget_q4#viewer@user:charlie means Charlie is a viewer of the Q4 budget document.
    • Crucially, the user can also be a group, represented by another tuple set, like group:finance#member. This allows for powerful and efficient modeling of indirect permissions and inheritance (e.g., "anyone in the finance group can view this document").
  2. Solving the "New Enemy" Problem: This is the core consistency challenge. Imagine Alice revokes Bob's access to a doc, then immediately adds a sensitive comment. If the authorization check for the comment uses stale data, Bob might see it. Zanzibar solves this with zookies, which are snapshots of the database state at a particular time.

    Zanzibar Access Control Flow
    This diagram shows how Zanzibar uses 'Zookies' (versioned tokens) to ensure consistency. When an access rule is changed (T0), a Zookie is created. Subsequent actions (T1) use that Zookie to check permissions, ensuring the change is respected. When Bob tries to access the resource later (T2) using a newer Zookie, he is correctly denied.

    By tying content modifications to a zookie, the application ensures that any future access check for that content is performed against a view of permissions that is at least as fresh as the content itself. This guarantees causality and prevents stale reads.

  3. Architecture for Scale: Zanzibar is globally distributed and heavily optimized with caching, request deduplication, and a separate subsystem (Leopard) for pre-computing and indexing deeply nested group memberships.

Being able to say, "For authorization, we could start with RBAC, but to handle fine-grained permissions at scale and ensure consistency, I would advocate for a centralized service inspired by Google's Zanzibar, using a tuple-based data model and a consistency mechanism like zookies," is a very strong Staff-level statement.


4. Data Protection

Protecting data is the final pillar. This involves securing data both as it travels over the network (in transit) and while it is stored (at rest).

Data in Transit

  • TLS Everywhere: All communication must be encrypted using Transport Layer Security (TLS). This applies not only to traffic from the client to your services but also to all service-to-service communication within your network.
  • Mutual TLS (mTLS): For service-to-service communication, mTLS is the gold standard. Not only does the client verify the server's identity, but the server also verifies the client's identity. This prevents unauthorized services from even making requests within your network.
  • Service Mesh: Implementing and managing mTLS certificates for hundreds of services is complex. A service mesh (like Istio or Linkerd) can automate this. It uses a "sidecar" proxy that sits alongside each service, transparently handling mTLS encryption/decryption and certificate rotation.
Microservices Architecture with Sidecar Pattern for Authentication/Authorization
This diagram shows a typical microservices architecture. The 'sidecar' pattern, shown here, is where a service mesh would inject its proxy to handle cross-cutting concerns like security. This proxy can enforce mTLS for all traffic entering and leaving the service, securing data in transit without any changes to the application code.

Data at Rest

  • Encryption: Sensitive data (e.g., Personally Identifiable Information - PII) stored in databases, object stores, or on disk must be encrypted.
  • Key Management: The biggest challenge with encryption at rest is managing the encryption keys. You should never store keys in code or configuration files. Use a dedicated Key Management Service (KMS) like AWS KMS, Google Cloud KMS, or HashiCorp Vault.
  • Envelope Encryption: This is a common pattern used by KMS. Instead of sending large amounts of data to the KMS to be encrypted, you:
    1. Generate a unique Data Encryption Key (DEK) locally for each piece of data.
    2. Use the DEK to encrypt the data.
    3. Ask the KMS to encrypt the DEK using a master key that never leaves the KMS.
    4. Store the encrypted DEK alongside your encrypted data.
      This is efficient and secure, as the master key is never exposed.

Auditing

Finally, a complete security model includes accountability. All security-sensitive actions (logins, permission changes, access to sensitive data) should generate immutable audit logs. This is crucial for forensic analysis, compliance, and detecting breaches. This ties directly back to our previous lesson on observability—these audit records are a critical type of log.


Conclusion

Today, we've constructed a robust, multi-layered security model that you can articulate in a system design interview. You have the framework to discuss security not just as a feature, but as a foundational aspect of system architecture.

Key Takeaways:

  • The Three Pillars: Structure your security discussion around Authentication (JWTs, refresh tokens), Authorization (RBAC/ABAC, Zanzibar for scale), and Data Protection (mTLS, encryption at rest with KMS).
  • Speak in Patterns: Use architectural patterns to frame your solution: API Gateway for centralized AuthN, Service Mesh for mTLS, and KMS for key management.
  • Know Your Trade-offs: Be ready to discuss the trade-offs, such as symmetric vs. asymmetric signing for JWTs or the complexity vs. power of different authorization models.
  • Aim for Staff+ Depth: Bringing in advanced, real-world examples like Google's Zanzibar demonstrates a level of knowledge that goes beyond standard interview preparation and shows you're thinking about these problems at the scale of a top-tier tech company.

Preview of the Next Lesson:
With our system designed, observable, and secured, the next logical step is to get it into production reliably. In our next lesson, we will learn to: Articulate a deployment and rollback strategy (e.g., blue-green, canary) for a critical service.