Skip to content

Interview PrepSecurity between services · Advanced

Service-to-Service Security ​

37. How do microservices authenticate each other? ​

The short answer

Each service needs a workload identity it can prove without a hand-copied password. The usual ways are mutual TLS, where both sides present certificates, often handled automatically by a service mesh; OAuth client credentials, where a service gets a short-lived access token from the identity provider for a specific audience; or platform identity, such as a Kubernetes service account token or a cloud role, exchanged for a token. The receiving service then checks the caller's identity and whether that caller may make this request. When a call is on behalf of a user, the user's identity travels separately, in a signed token.

orderscallerpaymentschecks both,then authorises① which service? mTLS certificate,or token with aud = payments② which user? signed user token,or an exchanged narrower token
Two questions on every internal call. ① proves the calling service is really orders. ② proves which customer the call is for. Payments needs both, and still decides on its own whether this request is allowed.

The mistake to avoid: "requests from inside the network are trusted". Then anyone who reaches one internal service, through a compromised pod or SSRF, can call every other service as any user (zero trust).

38. What are common service-to-service authentication approaches? ​

The short answer

From weakest to strongest: network trust, where anything inside the private network is accepted, which is not authentication at all; shared API keys or static secrets per service; signed JWTs from a shared signing key; OAuth 2.0 client credentials with short-lived, audience-restricted tokens from an identity provider; mutual TLS with automatically rotated certificates; and workload identity federation, where the platform vouches for the workload and no stored secret exists at all. Most mature systems combine mTLS for the connection with tokens for authorization and user context.

ApproachSecret stored?RotationRevocationStrength
Network locationNoneNot applicableNot applicableNone
Static API key per serviceYes, long-livedManualDelete the keyWeak
Shared-key HMAC JWTYes, sharedHard; every service holds itRotate the keyWeak to medium
OAuth client credentialsA client secret or private keyTokens expire in minutesAt the identity providerStrong
mTLS with a mesh or SPIFFECertificates, issued automaticallyHours or days, automaticStop issuingStrong
Platform identity, such as managed identitiesNonePlatform handles itPlatformStrongest

SPIFFE in one sentence. SPIFFE is an open standard that gives every workload an identity like spiffe://shop.example/ns/prod/sa/orders, and a short-lived certificate or token proving it, issued automatically by the platform. Service meshes such as Istio use it under the hood.

39. How do OAuth and mTLS compare for service-to-service communication? ​

The short answer

mTLS authenticates the connection: both sides prove which workload they are with certificates during the TLS handshake, and the channel is encrypted. It is transparent to application code when a service mesh handles it, but it says nothing about users or fine-grained permissions. OAuth authenticates each request with a token carrying the caller's identity, audience, scopes and, if needed, the end user. It needs application code to obtain and check tokens. They solve different layers, so strong designs use both: mTLS for workload identity and encryption, tokens for authorization and user context.

mTLSOAuth tokens
ProvesWhich workload holds the certificateWhich client, which audience, which scopes, which user
CheckedOnce per connectionEvery request
EncryptionYesNeeds TLS underneath
User contextNoYes
Fine-grained permissionNoScopes and claims
EffortA mesh does it; certificate management without oneToken fetching, caching and validation in code

Binding them together. OAuth's mTLS-bound tokens, RFC 8705, tie an access token to the client's certificate, so a stolen token is useless without the matching private key (mTLS).

40. What is API key authentication, and why are API keys often weaker than OAuth? ​

The short answer

An API key is a long random string the client sends with every request, in a header such as Authorization: Bearer sk_live_… or X-API-Key. The server looks it up to identify the client. It is simple and works well for server-to-server integrations. It is weaker than OAuth because the key is long-lived and used directly on every call, so a leak is valid until someone notices; it usually has broad access rather than narrow scopes; it identifies an application, not a user; and it is easy to paste into code and logs. Protect keys by hashing them, scoping them, rotating them and showing them once.

ts
import { randomBytes, createHash } from 'node:crypto'

export async function createApiKey(tenantId: string, scopes: string[]) {
  const secret = randomBytes(32).toString('base64url')
  const key = `sk_live_${secret}`                                               // (1)
  await apiKeys.insert({
    tenantId, scopes,
    prefix: key.slice(0, 12),                                                   // (2)
    hash: createHash('sha256').update(key).digest('hex'),                       // (3)
    expiresAt: addDays(new Date(), 365),
  })
  return key                                                                    // (4)
}

export async function authenticateApiKey(req: Request) {
  const key = req.get('authorization')?.replace(/^Bearer /, '') ?? ''
  const row = await apiKeys.findByHash(createHash('sha256').update(key).digest('hex'))
  if (!row || row.revokedAt || row.expiresAt < new Date()) throw new HttpError(401, 'Invalid API key')
  return row                                                                    // (5)
}
  1. A recognisable prefix, so secret scanners on GitHub and elsewhere can spot leaked keys.
  2. Store the first few characters to show in the dashboard, such as sk_live_8fK2….
  3. Store only a hash. A random 256-bit key does not need a slow hash; SHA-256 is enough.
  4. Show it once. It is never retrievable again.
  5. The row carries the tenant and scopes, so each request is limited to what that key may do.
API keyOAuth access token
LifetimeMonths or yearsMinutes
ScopeOften everythingRequested scopes only
Identifies a userNoCan
Sent on every callThe key itselfA short-lived token; the secret goes only to the token endpoint
Leak impactUntil revokedUntil the token expires

41. How do you design audit logging across services? ​

The short answer

An audit log records who did what, to which resource, when, from where, and with what result, for security investigations and compliance. Across services, define one event format, have every service emit audit events for sensitive actions, carry the actor, user and calling service, and a correlation ID through every hop, and ship events to a central, append-only, access-controlled store, separate from normal application logs. Make records tamper-evident, keep them for the period regulations require, never include secrets, and make them searchable by user, resource and time.

json
{
  "id": "aud_01JB8F2Q7T",
  "time": "2026-10-27T10:14:03.512Z",
  "actor": { "type": "user", "id": "u_7", "via": "support-console" },
  "onBehalfOf": { "type": "user", "id": "u_42" },
  "action": "order.refund",
  "resource": { "type": "order", "id": "ord_8812", "tenant": "acme" },
  "result": "success",
  "details": { "amountPence": 2550, "reason": "damaged item" },
  "source": { "service": "payments", "ip": "203.0.113.7" },
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736"
}

Reading it: support agent u_7, using the support console, refunded £25.50 on customer u_42's order. The traceId links this record to every log line and span of the same request across services (correlation IDs).

RuleWhy
One schema for every serviceSearchable together
Who, what, which, when, where, resultAnswers an investigator's questions
Actor and on-behalf-ofSupport staff acting for customers
Append-only store, restricted accessAttackers and insiders cannot erase their tracks
Separate from debug logsDifferent retention and access rules
No secrets or full card numbersThe audit log must not become a leak
Hash chaining or write-once storageEvidence that records were not altered

What to audit: logins and failures, permission and role changes, access to personal data, money movements, exports, admin actions, configuration and key changes.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Architecture & Distributed Systems
Structure
Data across services
Resilience
Communication
Security between services
Algorithms
Other topics
Nothing picked yet