Real Interview Questions for the Software Engineer at Kaspersky
NewInterview Q&A
Q&A-1What happens if you start a goroutine and call panic inside it? Will the goroutine stop or will the entire application stop?
Reported in Kaspersky interview: System Design, Principal
The 90-second answer
The entire application stops. An unrecovered panic in any goroutine terminates the program, not just that goroutine. The runtime prints the panic value and a stack trace for the panicking goroutine to stderr and exits with status 2. Other goroutines are killed mid-execution. Their deferred functions do not run.
recover only works in the same goroutine that panicked, inside a deferred function. A deferred recover in main does not save a worker goroutine.
// Go 1.22, checked against the runtime behaviour
package main
import (
"fmt"
"time"
)
func worker() {
defer func() {
if r := recover(); r != nil {
fmt.Println("worker recovered:", r)
}
}()
panic("malformed sample")
}
func main() {
go worker()
time.Sleep(100 * time.Millisecond)
fmt.Println("main still running")
}With that defer in worker, output is worker recovered: malformed sample followed by main still running. Remove the defer and the second line never prints. The process dies on the panic line.
What the runtime actually does
A panic starts unwinding the stack of the goroutine that called it. Deferred calls in that goroutine run in LIFO order. If one of them calls recover, unwinding stops, the panic value is returned, and that goroutine resumes after the deferred call returns. If no deferred call recovers, the runtime treats it as fatal for the process.
That distinction matters in a worker pool, which is the shape I would expect in a scanner or agent component. One bad input should not take down the pool.
| Scenario | Deferred recover in panicking goroutine | Result |
|---|---|---|
panic in worker, no recover | none | Whole process exits, code 2, other workers killed |
panic in worker, defer + recover in worker | present | Worker goroutine ends or continues, pool and main unaffected |
panic in worker, defer + recover only in main | wrong goroutine | Whole process exits, main deferred function never runs |
panic(nil) in Go 1.21 or later | none | Process exits, recovered value is *runtime.PanicNilError if recovered |
Failure modes to name in the interview
First, recovering too broadly. A recover that swallows the value and continues the loop can leave shared state half updated. In a scanning worker, that might mean a file handle left open or a result slice appended to before the panic. I recover at the narrowest boundary, log the value with a stack trace via runtime/debug.Stack(), mark the item failed, and let the worker move to the next item.
Second, panic during a panic. If a deferred function itself panics while unwinding, the new panic replaces the old one and unwinding continues from that deferred function. Code in the recovery path has to be simple and not allocate or dereference unchecked pointers.
Third, assuming recover catches runtime errors. It catches panics from panic, nil map writes, index out of range, and nil dereference, because those raise panics. It does not catch a fatal error such as an out of memory condition, a stack overflow, or a concurrent map write detected by the runtime. Those kill the process regardless of deferred functions. That is why a recover boundary is not a substitute for fixing the bug that caused the panic.
For a long running service I would also set a policy: worker goroutines that process untrusted input get a recover boundary per item, the main goroutine does not rely on one, and a panic that escapes a worker is treated as a crash to alert on, not as normal control flow. Using panic for routine errors like a missing file is a design smell. Return an error there and reserve panic for invariants that should never happen.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2What is the order of traversal of elements in a map container in Go?
Reported in Kaspersky interview: System Design, Principal
The 90-second answer
Go does not define an order for range over a map. The runtime randomizes iteration on every pass, so the same map can yield keys in a different sequence each time you loop over it. Code that needs a stable order has to sort the keys itself.
That randomization is deliberate. The Go spec leaves iteration order unspecified, and the runtime implements it by picking a random starting bucket and a random offset inside that bucket. Two consecutive loops therefore start at different points and wrap around, which breaks code that accidentally depends on insertion order or hash order.
package main
import "fmt"
func main() {
m := map[string]int{"alpha": 1, "beta": 2, "gamma": 3, "delta": 4}
for k := range m {
fmt.Print(k, " ")
}
fmt.Println()
}Run it repeatedly and the output changes, for example gamma alpha delta beta, then beta delta alpha gamma. Neither run is sorted and neither preserves the literal order in the source. A test that compares output from a raw map loop will flake for exactly this reason.
Getting a deterministic order
Collect the keys, sort them, then look values up in that order. For a map with string keys this is the usual pattern:
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
slices.Sort(keys) // Go 1.21+; sort.Strings before that
for _, k := range keys {
fmt.Println(k, m[k])
}Cost is O(n log n) for the sort plus O(n) to collect keys. For a small config map that cost is noise. For a hot loop over millions of entries, sorting on every pass is wasteful, so sort once and cache the key slice, or switch the data structure.
| Need | Use | Why |
|---|---|---|
| --- | --- | --- |
| Stable output, tests, serialization | Sorted key slice | Deterministic across runs and machines |
| Insertion order | Slice of keys maintained alongside the map, or an ordered map implementation | Go maps discard insertion history |
| Fast lookup only, order irrelevant | Plain map | No sorting overhead |
| Ordered iteration by value | Sort keys by the looked-up value | Map still gives no ordering guarantee |
Worked trace
Hypothetical run over the map above, labelled as illustrative because the runtime chooses the start point:
| Pass | Random start | Sequence produced |
|---|---|---|
| 1 | bucket for gamma | gamma alpha delta beta |
| 2 | bucket for beta | beta delta alpha gamma |
| 3 | bucket for alpha | alpha delta beta gamma |
Each pass visits every key exactly once. Randomization changes the starting point, it does not drop or duplicate entries.
Failure modes worth naming
Concurrent access is the sharp edge. Writing to a map while another goroutine iterates it can trigger fatal error: concurrent map iteration and map write and crash the process. Guard the map with a sync.RWMutex, or use sync.Map when contention is low and the access pattern is read-heavy. sync.Map still has no defined iteration order.
Deleting during iteration is safe in Go. A key deleted before it is reached will not be produced, and a key inserted during iteration may or may not be produced. That makes delete-while-ranging acceptable for cleanup, but it is a poor way to build a snapshot. Copy the keys first if the loop body mutates the map in ways you need to reason about.
If an interviewer pushes on why Go chose this, the answer is defensive design. Deterministic iteration in early programs let bugs hide, where code worked on one machine and broke when hash seeds changed. Randomizing the start makes accidental order dependence fail fast in tests instead of in production.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Which of the following are synchronization tools in Go? Channels, sync.WaitGroup, sync.Mutex, sync.Cond?
Reported in Kaspersky interview: System Design, Principal
The 90-second answer
All four count, but they solve different problems and I would not reach for them interchangeably. Channels are built into the language and synchronize by transferring values between goroutines. sync.Mutex, sync.WaitGroup and sync.Cond live in the sync package. Mutex gives mutual exclusion, WaitGroup waits for a counter to reach zero, and Cond waits for a predicate on shared state to become true. In a worker pool I default to channels plus a WaitGroup, use a Mutex when several goroutines touch the same struct, and only consider Cond when multiple waiters must sleep until that struct reaches a particular state.
Take a concrete shape: eight goroutines scan files, a coordinator collects results, and a reporter must not run until at least two results have arrived. That last requirement is where the choice matters.
| Tool | Blocks on | Wakes when | Use it for |
|---|---|---|---|
chan T | send with no receiver, or receive with no sender | counterpart arrives, or sender closes the channel | pipelines, fan-out, fan-in, cancellation with select |
sync.Mutex | Lock() while another goroutine holds it | holder calls Unlock() | a short critical section around a map, counter or struct field |
sync.WaitGroup | Wait() while counter is above zero | Done() calls bring the counter to zero | waiting for a known set of goroutines to finish |
sync.Cond | Wait() | Signal() or Broadcast() fires and the predicate holds on recheck | several waiters sleeping until shared state changes |
Mechanism and failure modes
A channel send blocks until a receiver takes the value, unless the buffer has room. A receive blocks until a sender provides a value or the channel closes. Only the sender side should close a channel. Sending on a closed channel panics, closing twice panics, and a receiver draining a closed channel gets the remaining values first, then the zero value with ok == false.
Mutex has no ownership. Any goroutine can unlock it, so the safe pattern is Lock() followed immediately by defer Unlock() in the same function. It is not reentrant. Locking twice from the same goroutine deadlocks. Copying a Mutex after first use copies its locked state, so embed it in a struct and use that struct by pointer.
WaitGroup is a counter with Add, Done and Wait. The bug I see most often is calling Add(1) inside the goroutine being waited on. If Wait() executes first it sees zero and returns while work is still running. Call Add() before starting the goroutine. Calling Done() more times than Add() drives the counter negative and panics.
Cond must be paired with a Locker, usually a Mutex, plus a predicate. Wait() atomically unlocks the locker and suspends, then relocks before returning. Signal() wakes one waiter and Broadcast() wakes all of them. Neither hands over the lock. The waiter has to recheck the predicate in a loop under the lock, because a wakeup alone does not prove the condition holds. That loop also covers a signal that fired before the waiter started waiting.
package main
import "sync"
func main() {
var mu sync.Mutex
cond := sync.NewCond(&mu)
count := 0
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
for count < 2 {
cond.Wait() // unlocks mu while suspended, relocks on wakeup
}
mu.Unlock()
}()
jobs := make(chan int, 2)
jobs <- 1
jobs <- 1
close(jobs)
for range jobs {
mu.Lock()
count++
cond.Signal()
mu.Unlock()
}
wg.Wait()
}Worked trace
| Step | Actor | State after step |
|---|---|---|
| --- | --- | --- |
| 1 | waiter goroutine | locks mu, sees count == 0, calls Wait(), releases mu |
| 2 | main, first job | locks mu, sets count = 1, calls Signal(), unlocks |
| 3 | waiter | wakes, relocks mu, rechecks count < 2, calls Wait() again |
| 4 | main, second job | locks mu, sets count = 2, calls Signal(), unlocks |
| 5 | waiter | wakes, relocks mu, rechecks count < 2 as false, unlocks, calls Done() |
| 6 | main | wg.Wait() returns |
When I would choose differently
If the reporter only needs the first result, a channel does this job with less code and no predicate to get wrong. I reach for Cond when the predicate is genuinely shared state, for example a bounded queue where several consumers sleep until an item appears and a producer signals them. Even there, a channel of queued items usually reads better and removes the missed-signal risk entirely.
When production hangs, a goroutine dump separates these cases quickly. Goroutines parked in chan send or chan receive point at a missing counterpart or a channel nobody closes. semacquire points at a Mutex that is never unlocked. sync.Cond.Wait with the predicate false points at a signal that never fires or a state change made without holding the lock. Naming which primitive is involved tells you which of those to look for first.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: