Microsoft Site Reliability Engineer (Junior Level) - Comprehensive Interview Preparation Guide
Microsoft's SRE interview process for junior-level candidates consists of a recruiter screening call, two technical phone screens focusing on infrastructure and incident response, and a five-part onsite interview loop covering behavioral assessment, Azure/infrastructure knowledge, system design fundamentals, troubleshooting scenarios, and practical technical problem-solving. The process emphasizes both foundational technical knowledge and practical operational experience relevant to Microsoft's Azure ecosystem.
Interview Rounds
Recruiter Screening
What to Expect
Initial phone call with a Microsoft recruiter to assess your background, motivation for the SRE role, career goals, and general fit with Microsoft's culture and values. This is a conversational round designed to understand your experience level, what attracted you to the role, and to provide you with information about the position and company. The recruiter will also assess your communication skills and enthusiasm for the role.
Tips & Advice
Be prepared with a clear 2-3 minute summary of your background and SRE journey. Research Microsoft's SRE practice and Azure services beforehand. Show genuine interest in the role and ask thoughtful questions about the team, responsibilities, and growth opportunities. Mention specific reasons why you're interested in Microsoft and the SRE discipline. Be honest about your experience level as a junior engineer and express your eagerness to learn. Keep energy and enthusiasm consistent throughout the call.
Focus Topics
Communication and Soft Skills
Communicate clearly, listen actively to questions, and respond thoughtfully. Avoid jargon-heavy explanations and explain technical concepts in an understandable way. Show good interpersonal skills and enthusiasm.
Practice Interview
Study Questions
Questions About the Role and Team
Prepare thoughtful questions about the SRE team at Microsoft, the types of systems you'd be working on, team size, on-call rotation structure, and typical responsibilities. Ask about growth opportunities and how the team approaches reliability.
Practice Interview
Study Questions
Microsoft and Azure Awareness
Demonstrate familiarity with Microsoft as a company, Azure as a cloud platform, and ideally have researched Microsoft's approach to reliability engineering. Show interest in Microsoft's technology ecosystem and why you want to work there specifically.
Practice Interview
Study Questions
Relevant Experience and Accomplishments
Highlight 1-2 specific accomplishments from your current or previous roles that are relevant to SRE work, such as automating a manual process, improving system reliability, or handling an incident response effectively. Focus on measurable outcomes.
Practice Interview
Study Questions
Understanding of SRE Discipline
Demonstrate basic knowledge of what SRE is, the distinction between SRE and DevOps, and key SRE concepts like error budgets, SLOs, and incident response. Show awareness of how SRE balances feature development with system reliability.
Practice Interview
Study Questions
Career Background and SRE Journey
Articulate your professional journey leading to SRE, highlighting relevant experiences in operations, infrastructure, or DevOps. Clearly explain what aspects of SRE interest you most and why you're transitioning into this role at this point in your career.
Practice Interview
Study Questions
Technical Phone Screen - Linux and Infrastructure Fundamentals
What to Expect
First technical phone screen conducted with a Microsoft engineer focusing on Linux system administration, infrastructure knowledge, scripting, and troubleshooting fundamentals. This round assesses your practical knowledge of operating systems, command-line proficiency, basic networking concepts, and your ability to automate routine tasks. You may be asked to explain how to troubleshoot common system issues or write a simple script to solve a problem.
Tips & Advice
Have a Linux environment or terminal accessible during the call (if permitted). Be prepared to work through scenarios interactively or explain how you would approach problems. Focus on practical, real-world examples from your experience. Don't worry if you don't know every answer—instead, demonstrate your problem-solving approach and willingness to learn. Review common Linux commands, file permissions, processes, networking tools, and basic shell scripting. Be ready to explain the 'why' behind your approach, not just the 'what'. For junior level, they expect foundational knowledge with room for growth.
Focus Topics
Log Analysis and Debugging
Demonstrate ability to read and interpret system logs, application logs, and dmesg output. Show how to use log analysis techniques to identify issues and understand system behavior over time.
Practice Interview
Study Questions
System Performance Troubleshooting
Know how to investigate system performance issues by examining CPU, memory, disk I/O, and network metrics. Understand tools like top, htop, iostat, vmstat, and how to read their output to identify bottlenecks and resource-constrained processes.
Practice Interview
Study Questions
Networking Fundamentals
Understand basic networking concepts including TCP/IP stack, DNS resolution, HTTP/HTTPS, ports, network interfaces, and common networking tools (ping, traceroute, netstat, ss, curl). Know how to diagnose network connectivity issues.
Practice Interview
Study Questions
Command-Line Proficiency and Shell Scripting
Show competence with common Linux command-line tools (grep, awk, sed, find, etc.) and ability to write basic shell scripts for automation. Demonstrate understanding of pipes, redirection, variables, and basic control structures in bash.
Practice Interview
Study Questions
Linux Fundamentals and System Administration
Demonstrate solid understanding of Linux operating systems including file systems, user/group permissions, process management, system services, and common system administration tasks. Be comfortable with concepts like systemd, kernel basics, memory management, and CPU scheduling at a conceptual level.
Practice Interview
Study Questions
Technical Phone Screen - Incident Response and Observability
What to Expect
Second technical phone screen with a Microsoft engineer focusing on incident response procedures, monitoring and observability concepts, performance troubleshooting approaches, and on-call responsibilities. This round evaluates your understanding of how to detect, respond to, and learn from incidents. You'll likely discuss hypothetical scenarios involving system failures, how you would approach troubleshooting, and your experience with monitoring tools and alerting systems.
Tips & Advice
Prepare specific examples of incidents you've experienced or helped resolve. Use the STAR method (Situation, Task, Action, Result) to structure your stories. Be ready to discuss your role in incident response, how you approached root cause analysis, and what you learned. Explain your understanding of the incident lifecycle: detection, diagnosis, mitigation, resolution, and post-incident review. Focus on demonstrating systematic thinking and how you remain calm under pressure. For a junior level candidate, show eagerness to respond to incidents and learn from them.
Focus Topics
Performance Troubleshooting and Capacity Planning
Know how to approach performance issues systematically, using metrics to identify bottlenecks, and how capacity planning helps prevent performance degradation. Understand concepts like latency, throughput, and utilization.
Practice Interview
Study Questions
Root Cause Analysis and Post-Incident Reviews
Demonstrate understanding of how to conduct effective root cause analysis (RCA) to understand why incidents occur. Know the principles of blameless post-incident reviews and how to extract learning from incidents to prevent future occurrences.
Practice Interview
Study Questions
Service Level Objectives (SLOs) and Error Budgets
Understand what SLOs are, how they relate to Service Level Agreements (SLAs), and the concept of error budgets. Know how error budgets influence decisions about feature development versus reliability improvements.
Practice Interview
Study Questions
Monitoring, Observability, and Alerting Concepts
Understand the difference between monitoring and observability. Know key concepts like metrics, logs, traces, and how they contribute to system visibility. Understand alert design principles, alert fatigue, and how to create meaningful alerts that indicate actual problems.
Practice Interview
Study Questions
Incident Response Process and Procedures
Understand the incident response lifecycle including detection, initial assessment, escalation, diagnosis, mitigation, resolution, and post-incident review. Know the roles and responsibilities during incidents, communication protocols, and how to prioritize actions based on severity.
Practice Interview
Study Questions
Onsite Interview - Behavioral and Microsoft Culture
What to Expect
First onsite interview focusing on behavioral assessment and cultural fit with Microsoft. The interviewer will explore your problem-solving approach, collaboration style, how you handle challenges, and how well you align with Microsoft's core values and culture. This round uses behavioral questions and may include scenario-based discussions to understand how you work in teams, handle ambiguity, and contribute to a positive team environment.
Tips & Advice
Research Microsoft's core values and culture. Prepare specific stories using the STAR method that demonstrate behavioral competencies. Show how you've collaborated with others, handled conflicts, learned from failures, and contributed to team success. Be authentic and specific—avoid generic or rehearsed-sounding answers. For a junior-level candidate, emphasize your eagerness to learn, willingness to help teammates, and ability to take feedback. Demonstrate that you're a team player who cares about reliability and quality. Ask thoughtful questions about the team culture and how they work together.
Focus Topics
Initiative and Continuous Improvement
Provide examples of where you've taken initiative to improve processes, automate manual tasks, or solve problems beyond your immediate responsibilities. Show your drive to make things better.
Practice Interview
Study Questions
Handling Challenges and Learning from Failure
Share experiences where you faced significant challenges or failures, what you learned from them, and how you applied those lessons. Demonstrate resilience and growth mindset. For junior level, show that you treat mistakes as learning opportunities.
Practice Interview
Study Questions
Problem-Solving Approach and Critical Thinking
Explain your systematic approach to problem-solving. Provide examples of complex problems you've tackled, how you broke them down, and how you arrived at solutions. Show your ability to think critically and ask good questions.
Practice Interview
Study Questions
Teamwork and Collaboration
Provide examples of how you've successfully collaborated with team members, developers, and other stakeholders. Show your ability to work cross-functionally, communicate effectively, and support teammates. For junior level, demonstrate willingness to seek help and contribute to team goals.
Practice Interview
Study Questions
Microsoft Core Values and Culture Fit
Demonstrate alignment with Microsoft's principles including a growth mindset, collaboration, integrity, and accountability. Show how your values and work style align with what Microsoft looks for in employees.
Practice Interview
Study Questions
Onsite Interview - Azure Services and Cloud Infrastructure
What to Expect
Second onsite interview focusing on Azure services, cloud infrastructure concepts, and how they apply to building reliable systems at scale. This interview assesses your understanding of Azure's service offerings, container orchestration with Kubernetes, infrastructure as code concepts, and practical application of these technologies for reliability. You may discuss architectural patterns, deployment strategies, monitoring within Azure, and how to design resilient systems on the cloud.
Tips & Advice
Familiarize yourself with core Azure services relevant to SRE work: Azure App Service, Azure Kubernetes Service (AKS), Azure Monitor, Log Analytics, Application Insights, and Azure Resource Manager. Understand basic Kubernetes concepts like deployments, services, pods, and namespaces. Be comfortable discussing infrastructure as code and tools like Terraform or ARM templates. Focus on practical applications rather than memorizing Azure documentation. Share experience with containers and orchestration if you have it. For a junior level, demonstrate foundational knowledge and express enthusiasm for learning the specifics of Microsoft's Azure platform.
Focus Topics
Azure Deployment and Scaling
Understand Azure's deployment options, how autoscaling works on Azure, and how to design systems that scale reliably. Know concepts like scale sets and how to plan capacity on the cloud.
Practice Interview
Study Questions
Container Orchestration with Kubernetes
Understand Kubernetes fundamentals including pods, deployments, services, namespaces, and ConfigMaps. Know how Kubernetes manages container orchestration and contributes to system reliability. Be familiar with basic kubectl commands.
Practice Interview
Study Questions
Infrastructure as Code (IaC) Concepts
Understand the principles of Infrastructure as Code and familiarity with tools like Azure Resource Manager (ARM) templates or Terraform. Know how IaC improves reliability, repeatability, and version control of infrastructure.
Practice Interview
Study Questions
Azure Core Services for SRE
Understand key Azure services including Azure Virtual Machines, App Service, Azure Kubernetes Service (AKS), Functions, and managed databases. Know the differences between these services and when to use each. Understand how these services contribute to building scalable and reliable applications.
Practice Interview
Study Questions
Azure Monitoring and Observability Tools
Know Azure Monitor, Log Analytics, Application Insights, and how they work together to provide observability into systems running on Azure. Understand how to create alerts, analyze metrics, and investigate issues using these tools.
Practice Interview
Study Questions
Onsite Interview - System Design Fundamentals
What to Expect
Third onsite interview focusing on basic system design and architecture principles relevant to building reliable, scalable systems. For junior-level candidates, this round assesses your understanding of fundamental design concepts, ability to think through tradeoffs, and how to apply reliability principles. You may be asked to design a simple system, explain how you would make a system more reliable, or discuss architectural patterns for handling failures.
Tips & Advice
Focus on fundamentals rather than complex distributed systems. Practice thinking through simple problems and discussing your approach. Understand concepts like redundancy, failover, load balancing, caching, and how they contribute to reliability. Be prepared to explain the tradeoffs of different design choices. Ask clarifying questions before jumping to solutions. For junior level, showing clear thinking and understanding of why certain design choices matter is more important than having a perfect solution. Draw diagrams to visualize your ideas. Discuss monitoring and alerting as part of your system design.
Focus Topics
Caching and Performance Optimization
Understand how caching improves performance and reduces load. Know different caching strategies, cache invalidation challenges, and tradeoffs of caching (consistency vs. performance).
Practice Interview
Study Questions
Monitoring and Alerting in System Design
Demonstrate that you think about monitoring and observability as part of system design, not as an afterthought. Discuss how you would monitor the system you design, what metrics matter, and how to alert on problems.
Practice Interview
Study Questions
Database Design and Data Consistency
Understand basic database concepts, CAP theorem principles, and tradeoffs between consistency and availability. Know when to use relational databases versus NoSQL and how these choices impact reliability.
Practice Interview
Study Questions
Redundancy and Fault Tolerance
Understand how redundancy improves reliability. Know concepts like active-active and active-passive configurations, failover mechanisms, and how to design systems that continue operating when components fail.
Practice Interview
Study Questions
Scalability and Load Balancing Principles
Understand how systems scale horizontally and vertically. Know the basics of load balancing, how to distribute traffic across multiple servers, and the challenges of maintaining consistency at scale. Discuss session management and statefulness in scaled systems.
Practice Interview
Study Questions
Onsite Interview - Troubleshooting and Problem-Solving Scenarios
What to Expect
Fourth onsite interview focused on practical troubleshooting and problem-solving abilities through scenario-based questions and hypothetical incident situations. This round evaluates how you systematically approach problems, communicate your thinking process, and arrive at solutions under realistic constraints. You may be presented with production incidents, performance issues, or infrastructure problems and asked how you would diagnose and resolve them.
Tips & Advice
Listen carefully to problem descriptions and ask clarifying questions before diving into solutions. Walk through your troubleshooting process step-by-step. Show how you would gather information, form hypotheses, and test them systematically. Think out loud so the interviewer understands your reasoning. Discuss tools you would use and why. Be comfortable saying 'I don't know, but here's how I would find out.' For junior level, demonstrating a methodical approach and good communication is more important than having immediate answers. Reference real incidents you've dealt with if applicable.
Focus Topics
Rollback and Mitigation Strategies
Discuss how you would approach rolling back a problematic deployment and mitigating issues while working on a permanent fix. Show understanding of different mitigation strategies for various types of failures.
Practice Interview
Study Questions
Application vs. Infrastructure Issues
Understand how to differentiate between application-level problems and infrastructure problems. Know what metrics and logs to look at to make this distinction and how to escalate appropriately.
Practice Interview
Study Questions
Communication During Incident Response
Demonstrate clear communication about what you're observing, what you've tried, and what you're going to try next. Show how you would keep stakeholders informed and ask for help when needed.
Practice Interview
Study Questions
Diagnosing Performance Issues
Show how to investigate performance problems by checking key metrics (CPU, memory, disk I/O, network). Understand the relationship between these metrics and application performance. Know how to identify whether issues are application-level or infrastructure-level.
Practice Interview
Study Questions
Systematic Troubleshooting Methodology
Demonstrate a structured approach to troubleshooting: gather information, form hypotheses, test them, and isolate the root cause. Show how you narrow down problems by understanding system components and their interactions.
Practice Interview
Study Questions
Onsite Interview - Technical Deep Dive and Practical Problem-Solving
What to Expect
Fifth and final onsite interview focusing on deeper technical knowledge and practical problem-solving. This round may involve writing code or scripts, designing a monitoring solution, or solving a more complex technical problem. The interviewer assesses your ability to implement solutions, code quality, and depth of technical understanding in areas relevant to SRE work such as automation, tooling, or infrastructure.
Tips & Advice
Be prepared to write functional code or scripts in a language you're comfortable with (Python, Go, Bash, etc.). Focus on writing clear, maintainable code with good error handling. Discuss your approach before writing and think through edge cases. For junior level, pragmatic, working code is valued over complex solutions. You may be asked to implement a monitoring exporter, write an automation script, or solve a practical infrastructure problem. Practice thinking through how to break down a problem into manageable pieces. Ask questions to clarify requirements before implementing.
Focus Topics
Configuration Management and Infrastructure Tooling
Understand how configuration management tools work and their role in SRE. Be familiar with concepts like declarative configuration and how tooling helps maintain consistency across infrastructure.
Practice Interview
Study Questions
Tool Development and Problem-Solving
Demonstrate ability to solve practical problems by building tools or scripts. Show how you approach breaking down a problem into manageable components and building a solution incrementally.
Practice Interview
Study Questions
Code Quality and Best Practices
Write clean, readable code with appropriate error handling and logging. Demonstrate knowledge of testing practices. Follow coding best practices for maintainability and reliability.
Practice Interview
Study Questions
Automation and Scripting for SRE
Demonstrate ability to write scripts or code that automates operational tasks. Understand how to write maintainable automation code with good error handling, logging, and documentation. Know when to automate and when manual intervention is appropriate.
Practice Interview
Study Questions
Monitoring and Metrics Collection
Understand how to implement monitoring solutions, write custom exporters or collectors, and integrate with monitoring systems. Know how to expose relevant metrics and logs from systems.
Practice Interview
Study Questions
Frequently Asked Site Reliability Engineer (SRE) Interview Questions
Describe, step-by-step, how a typical cloud load balancer and autoscaling group interact during a sudden traffic spike that increases requests/sec by 5x in one minute. Explain registration/deregistration, health checks, scale-out latency, connection queueing, and short-term mitigation options to avoid degraded user experience.
Sample Answer
Situation: Traffic suddenly spikes 5x in one minute to a service behind a cloud load balancer (LB) and an autoscaling group (ASG).
Step‑by‑step interaction (what happens and why):
- LB receives 5x requests/sec and begins distributing new connections to existing healthy targets. If per‑instance capacity is exceeded, request queueing or TCP backlog grows at the LB or nodes.
- LB health checks continue — healthy targets remain in rotation; overloaded instances may start failing checks (latency/timeouts) and be marked unhealthy and deregistered, reducing pool size and worsening load.
- ASG’s scaling policies observe metrics (CPU, RPS, custom latency). A target‑tracking or step policy triggers scale‑out: ASG requests new instances/containers from the cloud provider.
- Registration: once instances pass initial health (agent ready, app listening), they register with the LB (or LB autodiscovers). Only after passing LB health checks do they receive traffic.
- Scale‑out latency: includes instance launch time (VM/container startup), app initialization, JIT/connection pools, and LB health‑check warm‑up. This can be tens of seconds to minutes—creating a shortfall period.
- Deregistration/connection draining: when instances are removed (unhealthy or scaled in), LB drains existing connections per configured timeout so in‑flight requests finish.
Short‑term mitigation options to avoid degraded UX:
- Increase capacity at LB layer: raise max concurrent connections or add LB nodes if configurable.
- Reduce per‑instance startup and warm‑up: use pre‑baked images, lightweight containers, or warm pools to cut scale latency.
- Use proactive (predictive) scaling or step scaling: trigger earlier scale‑outs using RPS or queue length metrics instead of CPU.
- Enable connection queueing and circuit breakers: queue requests at edge and return quick 429s for overload to signal clients to back off.
- Graceful degradation & caching: serve stale cache, reduce feature load, disable nonessential work.
- Tune health checks and deregistration: lengthen health‑check thresholds slightly to avoid premature removal; enable slow‑start/warm‑up on LB so new instances ramp traffic gradually.
- Short bursts: serve requests from CDN, edge cache, or API gateway throttling to absorb spike.
- Emergency rules: temporarily increase ASG max size, enable surge capacity or spot/fleet fallback.
Key tradeoffs and recommendations:
- Aggressive health checks remove sick nodes fast but can intensify capacity loss—balance probe sensitivity.
- Warm pools and predictive scaling reduce user impact but cost more.
- Measure scale‑out latency and set autoscale trigger thresholds earlier (e.g., at 60–70% of instance RPS) and use request‑rate metrics for quicker detection.
Result: Combining faster instance start (warm pools), smarter metrics for earlier scaling, LB slow‑start, edge caching/throttling and temporary capacity increases minimizes user-visible errors during sudden spikes.
Explain the difference between breadth-first and depth-first traversal of a graph: what order nodes are visited in, what each one is typically implemented with, and their time and space complexity. When would you reach for one over the other?
Sample Answer
Direct answer
Breadth-first search (BFS) visits a graph level by level using a first-in-first-out queue: it fully explores every node at the current distance from the source before moving one edge farther out, which is exactly why the first time BFS reaches a node, it has found a shortest path to it in edge count (for unweighted graphs). Depth-first search (DFS) instead follows one path as far as it can, using a stack (explicit or via recursion), only backtracking once it hits a dead end. Both run in O(V+E) time and O(V) space on an adjacency-list graph with V vertices and E edges; reach for BFS when you need shortest paths or level-order information, and for DFS when you need to explore structure like cycles, connectivity, or an ordering that depends on finishing an entire subtree first, as in topological sort.
Structured elaboration
Mechanics
- BFS: enqueue the source, mark it visited, then repeatedly dequeue a node, and for each unvisited neighbor, mark it visited and enqueue it. The queue's contents at any point are exactly the current "frontier" one edge past the last fully-processed layer.
- DFS: push the source (or call recursively), mark it visited, and for each unvisited neighbor, recurse (or push) immediately, only returning to try the next neighbor after that whole branch is exhausted.
- Marking a node visited at the moment it's enqueued (BFS) or entered (DFS), not when it's dequeued or finished, avoids adding the same node to the queue or stack more than once.
Recursive versus iterative DFS
Recursive DFS is simpler to write, since the call stack does the bookkeeping for you, but it risks a stack overflow on a very deep graph (recursion depth is bounded by the language's call-stack limit, for example Python's default recursion limit of 1000). Iterative DFS with an explicit stack avoids that limit, at the cost of manually tracking which neighbors of a node remain to be visited.
Deep-and-narrow versus wide-and-shallow graphs
Both algorithms are O(V) space in the worst case, but the shape of the graph determines which one actually uses less memory in practice: on a long, narrow chain, DFS's memory stays proportional to the current depth, which can be far less than BFS's frontier at the widest level; on a short, very wide graph (many nodes one edge from the source), BFS's frontier can be large while DFS's stack stays shallow. Neither algorithm is unconditionally more memory-efficient; it depends on the graph's shape.
Cycle detection and topological sort
A DFS-based topological sort (or cycle check) needs three states per node, not a single visited flag: unvisited, in-progress (currently on the recursion stack), and finished. An edge to an in-progress node is a back edge and signals a cycle; an edge to an already-finished node is fine and doesn't indicate one. A binary visited flag can't tell these two cases apart.
Worked example
from collections import deque
adj = {0: [1, 2], 1: [3], 2: [3], 3: []}
def bfs(start):
visited = {start}
order = []
queue = deque([start])
while queue:
u = queue.popleft()
order.append(u)
for v in adj[u]:
if v not in visited:
visited.add(v)
queue.append(v)
return order
def dfs(start):
visited = set()
order = []
def visit(u):
visited.add(u)
order.append(u)
for v in adj[u]:
if v not in visited:
visit(v)
visit(start)
return order
if __name__ == "__main__":
print("BFS:", bfs(0))
print("DFS:", dfs(0))
Running this prints BFS: [0, 1, 2, 3] and DFS: [0, 1, 3, 2]. BFS visits both of node 0's neighbors (1 and 2) before going any deeper, reaching 3 only after the whole first layer is done. DFS instead commits to the first neighbor, 1, follows it all the way to 3, then backtracks and only picks up 2 afterward.
Trade-offs & pitfalls
- DFS does not generally find shortest paths in edge count; only BFS gives that guarantee on unweighted graphs.
- Forgetting to mark a node visited until it's dequeued (rather than when it's enqueued) in BFS lets the same node be enqueued multiple times through different neighbors, wasting work even though the final result stays correct once a visited check also guards processing.
- For weighted graphs where edge costs differ, neither plain BFS nor DFS finds the shortest path by cost; that needs Dijkstra's algorithm or A* search instead.
- A disconnected graph needs a traversal restarted from every unvisited node to cover every component; a single BFS or DFS call from one source only reaches that source's connected component.
Complexity
Time: O(V+E) for both, since every vertex and every edge is examined once. Space: O(V) for both (BFS's queue plus visited set; DFS's recursion stack or explicit stack plus visited set).
Edge cases
- Disconnected graphs: restart the traversal from each unvisited node to reach every component.
- Self-loops and multi-edges: a visited check naturally prevents a self-loop from causing infinite reprocessing.
- A single-node graph with no edges: both traversals just return that one node.
You have a pipeline of automation steps: provision VMs, deploy service, migrate DB, update DNS. Design a script-based orchestrator (not a full workflow engine) that runs these steps in order, records state so it can resume after failures, supports compensating rollback for each step, and exposes run status for operators. Describe data structures, state persistence, idempotency requirements, and how to implement resume and manual intervention.
Sample Answer
Direct answer
The defining constraint is explicitly 'not a full workflow engine' -- this needs enough structure to be safe (resumable, rollback-capable, observable) without the complexity of a general-purpose orchestration platform, which argues for a small, purpose-built state machine over adopting or building something heavier.
Data structures
from dataclasses import dataclass, field
from enum import Enum
class StepStatus(Enum):
PENDING = "pending"
RUNNING = "running"
DONE = "done"
FAILED = "failed"
ROLLED_BACK = "rolled_back"
@dataclass
class Step:
name: str
action: callable
compensate: callable
status: StepStatus = StepStatus.PENDING
@dataclass
class RunState:
run_id: str
steps: list # ordered list of Step, execution order == list order
current_index: int = 0
State persistence and resume
Persist RunState (as JSON, keyed by run_id) after EVERY step transition, not just at the end -- this is what makes resume-after-failure possible: on restart, load the persisted state, find the first step not yet DONE, and continue from exactly there rather than from the beginning. This is the same durable-checkpoint pattern demonstrated and verified elsewhere in this topic for resumable long-running automation, applied here at the step-sequence level rather than the per-item level.
Idempotency requirements
Each step's action MUST be idempotent (or resume could re-execute a step that actually completed but crashed before its status was persisted as DONE) -- 'provision VMs' needs to check-then-create rather than blindly create, 'update DNS' needs to set the record to the desired value rather than blindly append, following the same idempotency discipline covered throughout this topic. This requirement is non-negotiable for a resumable orchestrator: without it, a crash-and-resume can silently double-apply a step that only appeared to fail.
Resume and compensating rollback
def run(state: RunState):
for i in range(state.current_index, len(state.steps)):
step = state.steps[i]
step.status = StepStatus.RUNNING
persist(state)
try:
step.action()
step.status = StepStatus.DONE
state.current_index = i + 1
persist(state)
except Exception as e:
step.status = StepStatus.FAILED
persist(state)
_rollback(state, up_to_index=i)
raise RuntimeError(f"orchestration failed at step '{step.name}'") from e
def _rollback(state, up_to_index):
for i in reversed(range(up_to_index)):
step = state.steps[i]
if step.status == StepStatus.DONE:
step.compensate()
step.status = StepStatus.ROLLED_BACK
persist(state)
This mirrors the reverse-order compensation logic verified elsewhere in this topic for saga-style step coordination: only steps that actually completed (DONE) get compensated, in the reverse of their completion order, and each compensation is itself persisted so a crash MID-rollback can also resume correctly rather than needing to restart the whole rollback from scratch.
Manual intervention and run status
Expose RunState via a simple status query (which step is the run currently on, what's its history) so an operator can see exactly where a stuck or failed run is without reading logs, and support an explicit 'mark this step done manually' override for the case where a step's real-world effect actually succeeded but the automation's own tracking got out of sync (a manual DNS change made out-of-band during an incident, say) -- without this escape hatch, a genuinely-fine-in-reality but confused-in-state run has no path forward except editing the persisted state file by hand.
Trade-offs and pitfalls
The most common design mistake is persisting state only at run COMPLETION rather than after every individual step transition -- that shortcut looks fine until the process crashes mid-run, at which point there's no record of partial progress at all, and the whole resumability property this design exists to provide silently doesn't work.
Explain how imagePullSecrets, service accounts, and node-level credentials affect a pod's ability to pull images from private registries. Describe how Kubernetes resolves credentials and what you would check if pods across multiple namespaces fail to pull from a private registry.
Sample Answer
A pod's image pull uses the first credential source it finds, in order: pull secrets listed directly on the Pod spec, then pull secrets attached to the Pod's ServiceAccount, then whatever credentials the node itself can supply. If pods across several namespaces all start failing at once, the fault is almost never a per-namespace object (Secrets and ServiceAccounts are namespace-scoped, so a typo in one namespace would not explain a cluster-wide outage); look one level below namespaces, at the registry, the node credential mechanism, or a change that touched every namespace at once (a controller that syncs secrets, an expired shared token, or a registry-side block).
How credential resolution actually works
- Pod-level
imagePullSecrets. Ifpod.spec.imagePullSecretslists a Secret, the kubelet uses it. The Secret must be of typekubernetes.io/dockerconfigjson(a JSON blob shaped like Docker's~/.docker/config.json, holding registry hostname to username/password or token) and must live in the same namespace as the Pod, since Secrets are namespace-scoped objects. - ServiceAccount-attached secrets. If the Pod does not name its own
imagePullSecrets, Kubernetes checks the ServiceAccount the Pod runs as (pod.spec.serviceAccountName, defaulting todefault). If that ServiceAccount hasimagePullSecretsconfigured, an admission controller copies them onto the Pod at creation time. This is why teams standardize on patching the namespace'sdefaultServiceAccount rather than repeating the same Secret on every Pod spec. - Node-level credentials, last. If neither of the above supplies a credential, the kubelet falls back to whatever it can resolve on the node itself. On a modern cluster this is the kubelet's credential provider plugin mechanism (
--image-credential-provider-config/--image-credential-provider-bin-dir, generally available since Kubernetes 1.26): a small binary such as an ECR- or GCR-flavored credential provider that exchanges the node's cloud identity (an AWS IAM role, a GCP service account, workload identity) for a short-lived registry token, with no Secret object involved at all. This is a currency point worth being precise about: the older mental model of the kubelet reading a static/etc/docker/config.jsonon the node belongs to the dockershim era (dockershim was removed in Kubernetes 1.24, alongside direct Docker-socket calls); today the kubelet talks to containerd or CRI-O over the Container Runtime Interface (CRI), and credentials are resolved by the kubelet itself (via credential providers, or a static credential file for private on-prem registries) before it hands an authenticated pull request to the runtime, not by the runtime reading a Docker-specific file.
Debugging pods failing across multiple namespaces
- Confirm the blast radius and the error shape first:
kubectl get pods -A --field-selector=status.phase!=Running | grep -E 'ErrImagePull|ImagePullBackOff'
kubectl describe pod <pod> -n <ns>
Look for the actual reason string, not just the backoff state, for example:
Warning Failed 12s kubelet Failed to pull image "registry.example.com/app:v3":
rpc error: code = Unknown desc = failed to authorize: 401 Unauthorized
401 Unauthorized points at a credential problem specifically, as opposed to manifest unknown (wrong tag) or a network timeout (egress/firewall problem to the registry).
2. Check whether the affected namespaces share a common ServiceAccount pattern or a common Secret sync mechanism (many teams push the same dockerconfigjson Secret into every namespace via a controller such as kubernetes-reflector or an external-secrets operator); a bug or expiry in that shared pipeline explains a simultaneous multi-namespace break far better than coincidental per-namespace misconfiguration.
3. Decode and inspect one representative Secret:
kubectl get secret regcred -n <ns> -o jsonpath='{.data.\.dockerconfigjson}' | base64 -d
Check the token/password is not expired and the registry hostname key matches the image reference exactly (a mismatched hostname, for example a registry alias versus its canonical DNS name, is a common silent failure).
4. If node-level credentials are in play (no imagePullSecrets anywhere), check the node's credential provider instead of any namespace object:
kubectl logs -n kube-system <credential-provider or kubelet-adjacent pod, if run as one>
journalctl -u kubelet -n 200 | grep -i credential
A cluster-wide, sudden break here usually means the node's cloud identity lost registry permission (an IAM policy or role binding changed) rather than anything Kubernetes-side.
5. Rule out the registry itself: a registry-side rate limit, an account suspension, or a maintenance window will produce 401/403/429 responses to every caller regardless of namespace, which looks identical to a credential problem from the cluster's point of view.
Rotating credentials safely
Because the kubelet re-resolves credentials on every pull rather than caching them for a pod's lifetime, rotating the Secret's contents does not require restarting already-running pods; it only affects the next pull (a new pod, a restart after a crash, or a rolling update). The safe rotation sequence is: create the new Secret (or kubectl create secret docker-registry ... --dry-run=client -o yaml | kubectl apply -f - to update in place), verify a fresh pull succeeds in a canary namespace, then let the old credential expire on the registry side. For node-level (cloud IAM) credentials, rotation is handled entirely outside Kubernetes by the cloud provider's short-lived token issuance, which is one real advantage of workload-identity-based node credentials over static Secrets: there is no rotation to schedule at all.
Trade-offs and pitfalls
- Node-level credentials (cloud IAM / workload identity) eliminate Secret management and rotation entirely, but only work for registries the cloud provider integrates with (its own container registry); a private on-prem or third-party registry still needs an explicit
imagePullSecretschain. - A common wrong turn: assuming a Secret created in one namespace is visible to Pods in another. It is not. Teams either duplicate the Secret per namespace or run a sync controller; if that sync controller silently fails, only namespaces created after the failure are missing the Secret, producing a confusing "some namespaces work, some don't" pattern that looks like a Kubernetes bug but is a sync-pipeline gap.
- Patching only the
defaultServiceAccount is a common oversight when workloads intentionally use a non-default ServiceAccount; the pull secret has to be attached to whichever ServiceAccount the failing Pods actually reference. - Restarting kubelet or recreating pods "to fix it" without checking the actual
401/403reason wastes an incident cycle; the reason string in the pod event almost always tells you which of the three resolution layers to look at first.
Design an automated rollback approach for a stateful service whose release includes a database migration, using blue-green environments plus a read-only clone of the database for pre-migration verification. How do you minimize data loss and handle replication lag?
Sample Answer
Direct answer
Combining blue-green with a read-only database clone lets you validate a migration's effect on real, current data BEFORE committing to it on the live database: the clone gets the migration applied first, in isolation, so you catch a problem against production-representative data without any risk to the actual live system, and the blue-green switch itself still gives you fast rollback for the application layer once you do commit.
Structured elaboration
- Clone the production database (read-only) into an isolated environment and apply the migration to the CLONE first, validating both that the migration runs successfully and that the resulting data is correct, against real data characteristics (volume, distribution, edge cases) that synthetic test data might miss.
- If clone validation passes, apply the actual migration to production using the same discipline covered elsewhere (backward-compatible, expand-contract, batched for large tables), since the clone validated the LOGIC and DATA EFFECT, not the operational safety of running it against a live, concurrently-written system.
- Blue-green for the application layer: once the schema is safely migrated (backward-compatible, so both old and new app code can run against it), deploy the new application version to the green environment, validate it, and cut over traffic, keeping blue as an instant application-level rollback path.
- Minimizing data loss and handling replication lag: the production migration's write path needs an explicit boundary that prevents an in-flight write from landing in the gap between the old and new state. Concretely: take a fresh, final backup/snapshot immediately before the real migration begins (the earlier clone can be stale by the time the actual migration runs, so it isn't a substitute for this), run the migration as backward-compatible expand-contract in small, monitored batches so a failure partway through never forces discarding already-migrated data, and gate the blue-to-green traffic cutover on replication lag explicitly: define a maximum acceptable lag (for example, hold the cutover while green's replica lag exceeds a few seconds) and only cut traffic over once green has caught up to that threshold, rather than cutting over on a fixed timer regardless of lag. During the cutover moment itself, a brief write-quiesce or dual-write window (writes are accepted by blue and also applied to or replicated into green before green starts serving reads) closes the specific gap where a write landing in the last moments before cutover could otherwise be lost to whichever side ends up not serving traffic.
- Rollback scope: if a problem emerges post-cutover, blue-green gives fast APPLICATION rollback (switch back to blue), which is why replication should keep flowing from green back to blue for a defined window after cutover, so blue doesn't fall behind and a same-day switch-back doesn't lose whatever writes landed on green in the meantime; but if the issue traces to the migration itself rather than the application code, that's a data-layer rollback with its own considerations (covered by the backward-compatibility discipline that made the migration safe to begin with), not something the blue-green switch alone fixes.
Worked example
A migration converting a JSON blob column into normalized relational fields: applied first to a read-only production clone, revealing that roughly 2% of real production rows have malformed JSON that the migration's parsing logic doesn't handle, a data-shape problem synthetic test fixtures never surfaced. The migration logic is fixed to handle that edge case, re-validated against the clone, and only THEN applied to the actual production database with the same batched, lag-monitored discipline: a fresh pre-migration backup is taken, batches are throttled to keep replica lag under a defined threshold, and the blue-to-green traffic cutover waits until that threshold is met, with a brief dual-write window bridging the cutover moment itself so no write is lost in the gap; the application's blue-green cutover happens afterward, once the schema itself is confirmed safely migrated.
Trade-offs and pitfalls
Cloning a large production database is itself a real operational cost (storage, time to create the clone, and it can go stale relative to live production if there's a meaningful delay between cloning and actually running the real migration), so this technique earns its cost specifically for migrations complex or risky enough that catching a data-shape problem before it hits live data is worth the overhead; a simple, well-understood migration probably doesn't need it. The common mistake is treating clone validation as a substitute for the real migration's own operational safety discipline (batching, lag monitoring, a fresh pre-cutover backup, and an explicit lag threshold gating cutover) rather than as a complementary, earlier-stage check.
You built something meant to create transparency across teams, like a shared dashboard of problems and who owns them, but now teams are hiding issues or ignoring it because they're afraid of being called out. How do you fix that?
Sample Answer
Direct answer
Treat the hiding behavior as a signal that the dashboard is being used, or is perceived as being used, to assign blame, not just to surface facts. The fix starts with decoupling the data from performance judgment, not with re-explaining the dashboard. Bring the teams who are hiding issues into redesigning what gets shown and how, and restore full visibility gradually once trust is demonstrated, not all at once.
Structured elaboration
- Diagnose before redesigning. Find out whether the hiding is a reaction to an actual punitive incident (someone's numbers were cited unfavorably somewhere) or a perception problem with no real incident behind it. The fix differs: a real incident needs an explicit reversal, a perception problem needs a clearer signal from leadership.
- Decouple the data from evaluation. State explicitly, and have leadership repeat it, that the dashboard's numbers are never cited in individual or team performance reviews. Words alone will not fix it if the incident is real; the statement has to be paired with visible follow-through.
- Co-design the redesign. Bring the teams who are hiding issues into a working session on what gets tracked and how it is displayed. A redesign handed down without their input repeats the same trust problem in a new shape.
- Pair exposure with a path forward. Every flagged item should carry a remediation affordance, an owner and a next step, so appearing on the dashboard reads as "here is what is being done" rather than only "you are behind."
- Reintroduce gradually. Pilot the redesigned version with one or two teams first. Prove it is not being weaponized before rolling it back out to everyone; restoring full visibility immediately risks relapsing into the same hiding behavior before trust has actually rebuilt.
Worked example
Consider a flaky-test dashboard (the same pattern applies to an on-call load dashboard or a per-team bug-backlog view). After teams start mislabeling or hiding flaky tests, a short retro with a few team leads surfaces that two of them had their flaky-test counts cited unfavorably in a quarterly review months earlier, the actual punitive incident. Leadership issues an explicit statement that this data is excluded from reviews going forward, and the dashboard is redesigned with those teams to add a "remediation in progress" state instead of a raw open count. The redesigned dashboard is piloted with the same teams for one cycle, and only restored org-wide after that cycle shows honest reporting returning without any negative consequence.
Trade-offs & pitfalls
- Doubling down on enforcement, mandating reporting or adding compliance checks, tends to deepen the hiding rather than fix the underlying incentive.
- Quietly abandoning the dashboard rather than repairing it avoids the immediate conflict but permanently loses the transparency it was built to provide.
- Junior candidates tend to propose a better UX or better metrics for the dashboard. Senior candidates fix the trust and incentive problem first; the dashboard redesign is secondary to that.
- Restoring full visibility immediately after the fix, without a pilot, is a common pitfall: it risks a relapse into hiding before the teams have had a chance to see the new incentive hold up over time.
You need accurate 95th and 99th percentile queries over weeks or months of data without scanning raw points every time. Design an approach using pre-aggregation, materialized rollups, and approximate sketch algorithms (t-digest or HDR histograms), including how you'd merge partial sketches from many collectors and what accuracy you give up for that speed.
Sample Answer
Direct answer
Don't compute percentiles from raw points at query time. Have every collector maintain a local mergeable sketch (t-digest or an HDR histogram) over each rollup window, ship the sketch instead of the raw values, and merge sketches hierarchically (minute into hour, hour into day) so a query over weeks or months merges a small number of pre-combined objects instead of scanning raw samples. The accuracy you give up is bounded and tunable: it comes from the sketch's compression parameter, not from randomly dropping data, so you can trade a known amount of tail-percentile error for a known reduction in merge work.
Structured elaboration
Sketch choice:
- t-digest: variable bucket width, denser (more accurate) near the tails where percentile queries usually care most, mergeable, size controlled by a compression parameter δ (roughly, number of centroids).
- HDR histogram: fixed relative-error buckets across a configured value range, deterministic worst-case error bound, very fast to merge (array addition), best when the metric's range is known and bounded (for example request latency in milliseconds).
- Use t-digest for open-ended or skewed distributions; use HDR when the value range is known and the deterministic bound matters more than tail density.
Hierarchical rollups: each collector emits a 1-minute sketch. A rollup job merges 60 one-minute sketches into an hourly sketch, and 24 hourly sketches into a daily sketch. Retention is tiered: keep 1-minute sketches for 7 days, hourly for 30 days, daily beyond that. This is what makes "merge partial sketches from many collectors" tractable at high fan-in: each collector contributes one small sketch per window rather than a stream of raw points, and the merge tree does the aggregation once instead of at every query.
Merging at query time: the query picks the coarsest rollup tier that covers the requested range, merges those objects (t-digest merge is just concatenating and re-clustering centroids; HDR merge is bucket-wise addition), and computes the percentile from the merged sketch.
Handling very high fan-in (many collectors, very high ingest volume): the same hierarchy scales horizontally: instead of one job merging all collectors' sketches directly, shard collectors into groups, merge within a group first, then merge group-level sketches at the next tier. This bounds the fan-in of any single merge step regardless of how many collectors exist upstream.
flowchart LR
C1[Collector] -- 1-min sketch --> M1[Minute merge]
C2[Collector] -- 1-min sketch --> M1
M1 -- 60 merged --> H[Hourly sketch]
H -- 24 merged --> D[Daily sketch]
Q[Percentile query] -- picks coarsest tier covering range --> H
Q --> D
D -- retained 30d+ --> COLD[(Cold rollup store)]
Worked example
Merge count reduction. For a 30-day 99th-percentile query, merging at 1-hour granularity versus 1-minute granularity:
hourlyMerges=24×30=720 minuteMerges=1440×30=43,200 hourlyMergesminuteMerges=72043,200=60×Querying against hourly rollups means merging 60x fewer objects than querying against minute rollups, which is the primary win of hierarchical sketching: it shrinks the object count the query has to combine, not just the byte count of any one object.
t-digest size at a given compression. A t-digest with compression δ holds roughly δ centroids, each storing a mean and a count (two 8-byte doubles = 16 bytes):
digestBytes(δ)=16δAt δ=100: digestBytes=1,600 bytes per digest.
Storage over a year, at scale. For services=5,000 tracked series, keeping hourly digests for 365 days:
digestStorageYear=5,000×(24×365)×1,600 bytes=70.08 GBCompare to keeping raw 15s points for those same 5,000 series for a year, at 16 bytes/point:
rawStorageYear=5,000×1586,400×365×16 bytes=168.192 GB digestStorageYearrawStorageYear=70.08168.192=2.4×Worth being honest about what this number says: at δ=100, sketch storage is only 2.4x smaller than keeping the equivalent raw points, because each digest is representing many raw points (5,760 raw points/day per series versus 24 digests/day per series, so each digest stands in for 240 points). The real win from sketching at this compression level is the 60x merge-count reduction above, not storage. If storage is the binding constraint, dropping δ to 50 halves digest size (800 bytes) and roughly doubles the storage reduction factor to about 4.8x, at the cost of coarser centroid resolution and larger tail error.
Trade-offs & pitfalls
| Compression δ | Digest size | Tail accuracy | Storage reduction vs. raw (1yr, hourly) |
|---|---|---|---|
| 200 | 3,200 bytes | Best | ~1.2x |
| 100 | 1,600 bytes | Good | ~2.4x |
| 50 | 800 bytes | Coarser | ~4.8x |
Common wrong turns: merging sketches from different tiers as if they were interchangeable (a 1-minute sketch and an hourly sketch built with different compression settings can merge, but mixing merge granularities inconsistently across a query makes the resulting error bound harder to reason about, so keep the compression parameter fixed across a tier); treating a merged sketch's percentile as exact (it is an estimate with error concentrated where the sketch is coarsest, which for t-digest is the middle of the distribution, not the tails); and picking HDR for an unbounded-range metric (queue depth that can spike arbitrarily) where the fixed value range either clips outliers or forces an oversized histogram, when t-digest's variable bucketing is the better fit there.
Given the following log line format: '2025-05-01T12:34:56Z level=error srv=payments request_id=abc123 user_id=42 msg="checkout failed" latency_ms=562', write a Python function that parses arbitrary lines conforming to this structure into a dictionary, handles missing keys gracefully, and converts numeric fields. Provide example input and expected output.
Sample Answer
Direct answer
Split the leading timestamp token off, then pull every key=value pair with a regex that also handles quoted values containing spaces (like msg="checkout failed"), and convert values that look numeric into int/float. Keys that never appear in a given line simply never get a dict entry, so callers should use .get(key, default) rather than assuming every key is always present.
Approach
import re
KV_RE = re.compile(r'(\w+)=("[^"]*"|\S+)')
def parse_log_line(line):
"""Parse a line like:
2025-05-01T12:34:56Z level=error srv=payments request_id=abc123 ...
into a dict. The leading token (no '=') is treated as the timestamp.
Numeric-looking values are converted to int/float. Missing keys simply
do not appear in the result (callers should use dict.get with a default).
"""
parts = line.strip().split(" ", 1)
if not parts:
return {}
result = {}
if "=" not in parts[0]:
result["ts"] = parts[0]
rest = parts[1] if len(parts) > 1 else ""
else:
rest = line.strip()
for key, raw_val in KV_RE.findall(rest):
val = raw_val.strip('"')
if re.fullmatch(r'-?\d+', val):
val = int(val)
elif re.fullmatch(r'-?\d+\.\d+', val):
val = float(val)
result[key] = val
return result
line1 = ('2025-05-01T12:34:56Z level=error srv=payments request_id=abc123 '
'user_id=42 msg="checkout failed" latency_ms=562')
line2 = '2025-05-01T12:35:10Z level=info srv=payments msg="health check ok"'
for line in (line1, line2):
parsed = parse_log_line(line)
print(parsed)
print(" user_id:", parsed.get("user_id", "MISSING"))
Worked example (executed output)
{'ts': '2025-05-01T12:34:56Z', 'level': 'error', 'srv': 'payments', 'request_id': 'abc123', 'user_id': 42, 'msg': 'checkout failed', 'latency_ms': 562}
user_id: 42
{'ts': '2025-05-01T12:35:10Z', 'level': 'info', 'srv': 'payments', 'msg': 'health check ok'}
user_id: MISSING
Key points
- The regex
(\w+)=("[^"]*"|\S+)matches a bare key, then either a double-quoted value (captured without its quotes) or a plain whitespace-delimited value; this is what correctly keeps"checkout failed"as one value instead of splitting on the space inside it. - Numeric conversion is deliberately conservative: only strings that are entirely digits (with an optional leading
-) becomeint, and only a simple-?\d+\.\d+shape becomesfloat. Everything else, includingrequest_id=abc123, stays a string, which avoids accidentally coercing an alphanumeric ID that happens to start with digits. - Missing keys are absent, not
None. The second example line has nouser_idat all, andparsed.get("user_id", "MISSING")shows that explicitly, which is the "handle missing keys gracefully" behavior the question asks for.
Complexity
O(n) time and O(k) space, where n is the line's length and k is the number of key=value pairs, since the regex makes a single pass and each match does constant-time work.
Edge cases
- A key that appears twice: the current implementation lets the later occurrence overwrite the earlier one, since it's just a dict assignment in a loop; if you needed to preserve repeats, you'd collect values into a list instead.
- A value that looks numeric but isn't meant to be, like a zip code
user_zip=02139: this would be silently converted to the integer2139, losing the leading zero. If exact string preservation matters for some fields, you'd need a field-name allowlist for numeric conversion rather than converting anything digit-shaped. - Malformed tokens (a stray
=with nothing after it, or unbalanced quotes) simply fail to match the regex and are skipped rather than raising, which keeps the parser from crashing on one bad line in a large file.
Trade-offs & pitfalls
The main trade-off is permissiveness versus strictness: this parser is intentionally lenient (skip what doesn't match, coerce what looks numeric) because production log parsing usually needs to tolerate slightly malformed input rather than halt on it. The cost is exactly the zip-code-style edge case above, where "looks numeric" and "is semantically numeric" diverge; a stricter, schema-aware parser would need to know in advance which fields are genuinely numeric.
Create a small Bash script that accepts a systemd service name as an argument, checks whether the service is active using systemctl, and returns exit code 0 if active and non-zero otherwise. The script should validate input, print a human-friendly message, and avoid false positives (e.g., incorrectly reporting inactive services as active). Mention any permissions needed to run the check.
Sample Answer
Approach: validate argument, normalize unit name (append .service if missing), call systemctl is-active --quiet --unit to avoid output parsing, print human-friendly messages, and return 0 only when systemctl reports active. Note: systemctl is-active is generally readable by non-root; however, querying some units or private system namespaces may require root.
#!/usr/bin/env bash
# check-service.sh - exit 0 if service is active, non-zero otherwise
set -u
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <service-name>"
exit 2
fi
unit="$1"
# normalize: allow "nginx" or "nginx.service"
if [[ "$unit" != *.service && "$unit" != *.socket && "$unit" != *.target ]]; then
unit="${unit}.service"
fi
# Use --quiet so we rely on exit code not text (avoids false positives)
if systemctl --no-pager is-active --quiet -- "${unit}"; then
echo "Service '${unit}' is active."
exit 0
else
# Provide reason by asking is-active without --quiet for user info
state=$(systemctl --no-pager is-active -- "${unit}" 2>/dev/null || echo "unknown")
echo "Service '${unit}' is NOT active (state: ${state})."
exit 1
fi
Permissions: reading unit state usually works as non-root. If you get "Access denied" or checks against system-wide/private units fail, run as root (sudo) or ensure your user has permission to query systemd for that scope.
As part of compliance you must audit changes to /etc/sudoers. Describe how to configure auditd to watch the file and tag events with a custom key, how to query recent changes and extract the user/process that made the modification, and how to forward these audit logs to a central SIEM pipeline.
Sample Answer
Situation: You need tamper-evident auditing for /etc/sudoers, be able to query who/what changed it, and forward events to a central SIEM.
- Configure auditd to watch /etc/sudoers
- Add a rule (persistent):
- Edit /etc/audit/rules.d/99-sudoers.rules and add:
-w /etc/sudoers -p wa -k sudoers_mod - Explanation: -w watches the path, -p wa watches writes and attribute changes, -k tags events with the key sudoers_mod.
- Edit /etc/audit/rules.d/99-sudoers.rules and add:
- Load rules:
sudo augenrules --load
or
sudo systemctl restart auditd
- Query recent changes & extract user/process
- Find events by key (human-readable):
sudo ausearch -k sudoers_mod -i --start recent - Show file modification syscall events and include user/process fields:
sudo ausearch -k sudoers_mod -i --raw | ausearch -i -k sudoers_mod
or directly filter SYSCALL records for today:
sudo ausearch -k sudoers_mod -i -ts today -m SYSCALL | aureport -f - Extract who (auid/uid) and process (pid/exe):
sudo ausearch -k sudoers_mod -i -ts today -m SYSCALL -sv no
| awk -F' ' '/node=|type=SYSCALL/ {print $0}'
| sed -n 's/.auid=([0-9])./auid:\1/p; s/.uid=([0-9])./uid:\1/p; s/.pid=([0-9])./pid:\1/p; s/.exe="(.)"./exe:\1/p' - Simpler example to see important fields:
sudo ausearch -k sudoers_mod -i -ts today | aureport --summary -i - Note: map auid -> username via getent passwd (auid=4294967295 means anonymous/kernel). For automation, parse audit JSON (see next).
- Forward audit logs to a central SIEM
Option A — Filebeat/Auditbeat (recommended):
- Use Elastic's auditbeat or Filebeat audit module to tail /var/log/audit/audit.log and forward to Kafka/Elasticsearch/Logstash.
- Install auditbeat on host, enable auditd module, configure output:
output.elasticsearch or output.logstash or output.kafka - Advantages: structured events, TLS, batching, backpressure.
Option B — audispd-forward or audisp-remote:
- Install auditbeat on host, enable auditd module, configure output:
- Configure /etc/audisp/plugins.d/au-remote.conf to forward to a remote auditd receiver (audisp-remote/audit-remote daemon). Use TLS and firewall rules. This sends native audit protocol.
Option C — rsyslog/imfile: - Use rsyslog to read /var/log/audit/audit.log (imfile) and forward via RELP/TCP to SIEM: less preferred (less structured).
Best practices for SIEM:
- Ship structured JSON when possible (Filebeat/Auditbeat).
- Use TLS, authentication, and mutual certs.
- Preserve seq numbers/timestamps and hostname; include the audit key as a field (sudoers_mod).
- Rate-limit/alert on rapid changes and correlate with sudo, ssh logins (auid/uid), and process exe.
Example Filebeat snippet:
filebeat.inputs:
- type: log
enabled: true
paths: /var/log/audit/audit.log
processors: - decode_json_fields: { fields: ["message"], target: "audit" }
output.logstash:
hosts: ["siem.example.com:5044"]
Outcome: persistent audit rule with key sudoers_mod, use ausearch/aureport to identify actor (auid/uid, pid, exe), and forward logs securely to SIEM with Filebeat/Auditbeat or audisp-remote for centralized alerting and compliance reporting.
Recommended Additional Resources
- Site Reliability Engineering: How Google Runs Production Systems (O'Reilly) - foundational SRE concepts
- The Phoenix Project by Gene Kim - DevOps and operations mindset
- Azure Fundamentals (AZ-900) learning path on Microsoft Learn - Azure services overview
- Kubernetes Official Documentation and tutorials - container orchestration fundamentals
- Linux Academy or Linux Foundation courses - Linux system administration skills
- Monitoring and Observability resources: Prometheus documentation, ELK stack guides, Grafana tutorials
- OWASP Top 10 and security best practices - infrastructure security considerations
- Incident Response and Post-Mortem Best Practices - blameless postmortems and learning culture
- Microsoft Azure SRE GitHub repositories and documentation
- Practice platforms: LeetCode for coding skills, system design discussion communities
Search Results
SRE(Site Reliability Engineer) Interview Questions (2025)
1. What is SRE? · 2. What is DevOps? · 3. SRE vs DevOps: What's the Difference Between Them? · 4. Can you explain data structures and also describe ...
Site Reliability Engineer (SRE) Interview - Microsoft - Blind
Is there a typical loop rounds for SREs in Microsoft? - What to expect in the coding rounds? Is it more of leetcode problems?
50 Site Reliability Engineer (SRE) Interview Questions 2025
Q1. Differentiate between DevOps and SRE. · Q2. Why do you want to do a job in SRE? · Q3. Do you know anything about SLO? · Q4. What is Data ...
Microsoft Site Reliability Engineer Interview Questions - Exponent
Review this list of Microsoft site reliability engineer interview questions and answers verified by hiring managers and candidates.
Azure Site Reliability Engineering Interview Questions - YouTube
Ace your Azure SRE interview. This video covers Azure SRE interview questions and answers for freshers and experienced candidates.
Microsoft Site Reliability Engineer interview questions (2025)
All Microsoft Site Reliability Engineer interview questions asked in 2025. Contributed by recent candidates and verified by Site ...
Site Reliability Engineer (SRE) Interview Preparation Guide - GitHub
A collection of questions to practice with for SRE interviews · SRE Interview Questions · Sysadmin Test Questions · Kubernetes job interview questions · DevOps ...
This interview preparation guide was generated using AI-powered research from the sources listed above. While we strive for accuracy, we recommend verifying critical information from official company sources.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Site Reliability Engineer (SRE) jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs