Backend Interview Cockpit

Record vs Class

Record = value-based equality · Class = reference identity by default

Records are useful for immutable/data-oriented models and support with expressions.

“The main difference is the default equality semantics. Classes use reference equality by default, while records use value-based equality.”

ref / out / in

ref = read/write · out = must assign · in = readonly reference
  • ref: caller initializes, callee can modify.
  • out: caller need not initialize, callee must assign.
  • in: readonly reference, useful for large structs.

Task vs Thread

Task ≠ Thread

Thread is an execution unit. Task is a higher-level abstraction representing work that may complete later and does not require a dedicated thread.

“A Task represents an operation that may complete in the future and doesn't necessarily have a dedicated thread.”

ThreadPool

Reusable threads managed by .NET

Creating threads is expensive. With async I/O, a thread does not remain blocked while waiting and can serve other work.

CancellationToken

Cooperative cancellation

Source requests cancellation; token communicates it. Propagate request tokens through controller → service → repository → I/O.

Task.WhenAll

Start independent tasks → await all concurrently

Do not confuse tasks with threads. Same EF Core DbContext should not run concurrent operations.

IEnumerable vs IQueryable

IEnumerable = .NET enumeration · IQueryable = translatable query

With EF, build filters before materialization so the provider can translate them to SQL.

ToList too early

Materialize after filtering

db.Players.ToList().Where(...) may load the full table. Prefer db.Players.Where(...).ToList().

First vs Single

First = give me first · Single = there must be at most/exactly one

OrDefault changes the zero-result behavior. Single/SingleOrDefault throw if multiple rows match.

Stack vs Heap

Stack frames for calls · managed heap for objects

Value types are not always on the stack. A value-type field inside a heap object lives with that object.

Boxing

Value type → managed object allocation

Boxing can allocate on the managed heap and increase GC pressure.

Dependency Injection

Provide dependencies from outside · reduce coupling · improve testability
“A class receives its dependencies from the outside instead of constructing them itself.”

Authentication vs Authorization

Authentication = who are you? · Authorization = what can you do?

401 vs 403

401 = credentials/identity missing or invalid · 403 = known identity, forbidden

PUT vs PATCH

PUT = full replacement/update · PATCH = partial update

PUT is idempotent by HTTP semantics.

Middleware

HTTP request/response pipeline

Can inspect/modify request/response, call next, or short-circuit. Order matters: authentication before authorization.

Idempotency

Same operation N times → same resulting state as once

Important for retries after timeout/communication failure. Often uses operation/message IDs and unique constraints.

Exception Handling

Don't swallow exceptions

Catch when you know how to handle. Preserve stack with throw;, not throw ex;.

SQL slow?

Measure first: execution plan, indexes, scans, joins, sorts, locks, volume
“I would not optimize blindly. I would inspect the execution plan and identify the actual bottleneck first.”

Sargability

Predicate allows efficient index use

Avoid functions/conversions on indexed columns when possible. Example: range predicates on dates instead of YEAR(Date)=....

Clustered / Nonclustered

Clustered organizes table rows by key · Nonclustered = separate structure + row locator

SQL Server concept. One clustered index per table; multiple nonclustered indexes.

INNER / LEFT JOIN

INNER = matching rows only · LEFT = all left rows + NULLs when no right match

WHERE / HAVING

WHERE filters rows before grouping · HAVING filters groups after aggregation

Optimistic Concurrency

No lock while working · detect conflict on write

Version/timestamp or conditional UPDATE. 0 affected rows can signal conflict.

Pessimistic Concurrency

Lock resource during operation

Useful when conflicts are frequent or exclusive access is required.

Race Condition

Result depends on timing/order of concurrent access to shared state

Lost update is a classic example.

Deadlock

A waits for B · B waits for A

Reduce risk with consistent lock order, short transactions and minimal lock duration.

Horizontal Scaling

Stateless API + multiple instances + load balancer

Move shared state to DB/Redis/broker. Containers package; orchestrators/platforms scale.

Monolith vs Microservices

Monolith = simpler operations · Microservices = independent deploy/scale + distributed complexity

Microservices add timeouts, retries, partial failures, data consistency, messaging and observability concerns.

Cache-aside

Read cache → miss → DB → populate cache

On write, invalidate/update cache depending consistency requirements.

Cache Consistency

Ask: how stale can this data be?

Use TTL, invalidation, events/outbox, retries depending business requirements.

Dependency Inversion

Depend on abstractions, not concrete implementations

DI is a technique that can help implement DIP.

Testing Strategy

Unit = fast/isolated · Integration = components together · E2E = full flow

Don't mock everything automatically; mock where isolation adds value.

Message Broker

Infrastructure between producer and consumer

Receives, stores/routes and delivers messages. Examples: RabbitMQ, Azure Service Bus.

Queue vs Pub/Sub

Queue = one worker handles item · Pub/Sub = multiple subscribers receive event

Pub/Sub is a communication pattern; RabbitMQ is a broker that can implement messaging patterns.

Why async messaging?

No immediate response needed · temporal decoupling · buffering · retries · resilience

Trade-offs: eventual consistency, duplicates, ordering and observability complexity.

Transactional Outbox

Business change + outbox row in SAME DB transaction

A worker later publishes/processes the pending event and retries safely.

“The outbox makes the intent durable even if the external publish or cache invalidation fails.”

At-least-once

Don't lose message · duplicates possible → idempotent consumer

At-most-once

No duplicates · message may be lost

Eventual Consistency

Temporary divergence → eventual convergence

Acceptable when business can tolerate staleness/delay.

Retry / Timeout / Circuit Breaker

Timeout = stop waiting · Retry = try again · Circuit breaker = stop calling failing dependency temporarily

Circuit: closed → open → half-open → recovered or open again.

Azure Hosting

VM = control · App Service/Container Apps = managed · AKS = Kubernetes

Secrets

Use Key Vault / secret manager · never bake secrets into image

Redis

Hot reads · cache · TTL · invalidation

Ask consistency requirements before caching.

Messaging

Azure Service Bus for durable messaging · Event Grid for event distribution scenarios

Observability

Logs + metrics + traces

Azure Monitor / Application Insights; OpenTelemetry for vendor-neutral instrumentation.

Docker

Image = immutable package · Container = running instance

Docker packages and runs; orchestration/platform handles dynamic scaling.

Kubernetes

Desired state orchestration

Deployment manages replicas; Service gives stable access; scheduler replaces pods; node scaling is separate from pod scaling.

Health Checks

Liveness = should restart? · Readiness = can receive traffic? · Startup = has app started?

Rolling Deployment

Gradual replacement while serving traffic

Use readiness checks and graceful shutdown/draining.

Blue/Green / Canary

Blue/Green = switch environments · Canary = small traffic percentage first

CI/CD

Build → test → package → deploy → verify

Automate repeatable delivery and keep rollback strategy.

System Design Opening

Clarify requirements before choosing architecture
  • Traffic / concurrency?
  • Read vs write ratio?
  • Latency target?
  • Consistency requirements?
  • Failure tolerance?

Typical Scalable Backend

LB → stateless APIs → DB + Redis + broker

Add replicas, partitions or async work only when measurements justify them.

Database Bottleneck

Queries/indexes first → caching/read replicas → partition/shard only if needed

Hot Key / Cache Stampede

Single-flight / per-key lock · stale-while-revalidate · TTL jitter for many-key expiry

Read Replicas

Scale reads · beware replication lag

Consider read-your-writes requirements.

Purchase Flow

DB transaction for critical state + outbox for async side effects

Use idempotency for retries/duplicate messages.

Realtime / Gaming

Authoritative server · latency-aware design · persist only what must be durable

Keep hot match state in memory, use durable events/checkpoints as appropriate.