Real Interview Questions for the Software Engineer at ASML
NewInterview Q&A
Q&A-1Why do you want to join ASML?
Reported in ASML software engineer interview questions · UIRound
I want to join ASML because the software there is on the critical path for yield, and I want that kind of accountability. In my last role I worked on a motion controller where a missed deadline did not return an error, it scrapped the part in the fixture. Lithography is the same problem at a tighter tolerance. The stage, the EUV source and the dose control have to hold their budgets on every exposure, and the applications software that corrects overlay and dose is where a lot of the gain between machine generations comes from. ASML is also the sole supplier of EUV systems, so the work goes into fabs making leading edge logic and memory. I would rather be measured against yield data from a customer fab than against a feature adoption chart.
What I bring is experience with deterministic code and with systems that cannot be restarted casually. On the controller I owned the loop that read encoders, computed the correction and wrote the actuator output inside a fixed period. We budgeted it on the target hardware, not on a development machine. For a 250 microsecond period we allowed 40 microseconds for input, 90 for the calculation and 30 for output, and we treated the remaining 90 microseconds as margin we were not allowed to spend on logging. Logging went through a lock free buffer and was flushed by a lower priority task. That discipline is what I want to keep using.
I also know the costs of this kind of work, and I am choosing them with my eyes open.
| What attracts me | What it costs |
|---|---|
| A change can be traced to metrology and yield in a fab | Feedback takes months, because hardware integration and customer qualification come before any production effect |
| Machines stay in service for many years, so design decisions have to last | A design mistake is expensive to recall, and a service engineer may have to fix it on site |
| The installed base gives a large, real dataset for diagnostics | That dataset is constrained by customer confidentiality and by what can be collected without disturbing the machine |
If I wanted to ship a user facing change every week, or to work only on cloud scale systems where a bad deploy can be rolled back in minutes, this would be the wrong job for me. I have had enough of short cycles to know I prefer the slower loop, provided the problem is hard enough to justify it. The relocation to the Netherlands and the on site constraints in customer fabs are part of that same choice. I am not looking for a company where the hardware is a commodity and the software is a wrapper.
A concrete example of the failure thinking I would bring: on the controller, an encoder sample that arrived late was not treated as a slightly stale value. We timestamped each sample, and if the gap exceeded one period the watchdog held the last valid output, flagged the cycle in the trace and raised a fault after three consecutive gaps. The operational cost of getting that wrong was a scrapped part and a manual inspection, so we tested it by injecting dropped samples in the test rig and checking that the safe state was reached within one period. I would expect the same approach here, with the added cost that a fault can idle a machine in a customer fab.
I want to start close to the machine, where I can see a change pass integration testing, run on a system and show up in fab data. That loop, from commit to yield, is the reason I am applying to ASML rather than to a company where software is easier to change and easier to ignore.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Explain the difference between process and thread?
Reported in Software Engineer interview at ASML
The 90-second answer
A process is an instance of a program with its own virtual address space, file descriptors, signal handlers and scheduling identity. A thread is a unit of execution inside a process. Threads in the same process share the heap, globals, open files and the address space, and each has its own stack, registers, program counter and thread-local storage.
That sharing is the whole trade-off. Threads communicate by reading and writing shared memory, which is fast and cheap, but a race, a deadlock or a segfault in one thread can corrupt or kill the whole process. Processes communicate through explicit channels such as pipes, sockets or shared memory segments, which costs more to set up and to copy data across, but the kernel enforces isolation between them.
In an ASML controller I would use both deliberately. Separate processes for subsystems that must not take each other down, for example stage motion, laser control and dose control, each with its own watchdog. Threads inside one of those processes for parallel work that shares state tightly, for example polling encoders while computing a trajectory, with explicit locking and a real-time scheduling policy.
| Aspect | Process | Thread |
|---|---|---|
| Address space | Private, isolated by the kernel | Shared with all threads in the process |
| Stack and registers | One stack per process | One stack per thread |
| Creation cost on Linux | fork plus page table setup, typically hundreds of microseconds to a few milliseconds depending on address space size | clone with shared memory, typically tens of microseconds |
| Context switch | Flushes or switches page tables and TLB entries, roughly 1 to 10 microseconds in simple cases, more with large working sets | Switches stack and registers only, usually cheaper |
| Communication | IPC: pipes, Unix sockets, shared memory with explicit synchronisation | Shared variables, mutexes, condition variables, atomics |
| Failure isolation | A crash in one process does not corrupt another | A crash or data race in one thread can corrupt the whole process |
| Resource limits | Counted per process for memory, CPU and file descriptors | Counted per process, shared across threads |
What that looks like in code
Threads share a counter, so the increment must be synchronised. Processes do not share it at all, so each gets a copy on fork.
// C++17, checked with g++ -std=c++17 -pthread
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
std::atomic<long> shared{0};
int main() {
std::vector<std::thread> workers;
for (int i = 0; i < 4; ++i) {
workers.emplace_back([] {
for (int j = 0; j < 100000; ++j) shared.fetch_add(1);
});
}
for (auto& t : workers) t.join();
std::cout << shared << '\n'; // 400000, every thread saw the same variable
}With fork, the child would see its own copy of shared as it was at the fork point. Writes in the child would never appear in the parent. That is why process code needs a pipe or a shared memory segment created before the fork, plus a lock or a lock-free protocol around it.
Failure modes I would name in the interview
A data race on shared memory is the classic thread bug. Two threads update a stage position without a lock, the value ends up torn or stale, and the symptom appears far from the cause as a positioning error. Detection is ThreadSanitizer in test builds and, in production, invariants checked on the shared state, such as monotonic timestamps that must never go backwards.
Priority inversion is the real-time version of the same problem. A low priority thread holds a mutex that a high priority motion thread needs, while a medium priority thread preempts the low one. The high priority thread waits indefinitely. The fix is priority inheritance or priority ceiling on the mutex, which Linux provides through PTHREAD_PRIO_INHERIT and through real-time mutexes in the kernel.
A segfault in a thread kills the process, so a thread that parses untrusted input or talks to a vendor library with known memory bugs belongs in its own process behind a narrow IPC interface. Then the supervisor can restart that process, log the faulting address and keep the rest of the machine running.
When not to use threads
If the work is CPU bound in a language with a global interpreter lock, such as CPython, threads will not parallelise it. Use processes there, or move the hot loop to C or C++. If the work is mostly waiting on I/O, threads are fine and cheaper than a process per connection. If isolation matters more than sharing speed, for example a safety interlock that must keep running when a logging process dies, use a process and accept the IPC cost.
So the short version I would give live: processes give isolation at the cost of explicit communication, threads give cheap sharing at the cost of shared failure. A good design picks per subsystem, not by habit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3How would you design a scalable system for handling large data streams?
Reported in Software Engineer interview at ASML
The 90-second answer
I would start by pinning down four numbers, because they change the design completely: sustained ingest rate, peak burst, end-to-end latency budget, and retention. For an ASML style system I will assume sensors and metrology from lithography tools plus fab events, sustained 500 MB/s to 1 GB/s, bursts of 3x for a few minutes, analytics latency under 5 seconds, and 7 days hot retention. If this were a hard real-time control loop I would not put it on a general streaming platform at all. Control stays on the tool, deterministic and local. The stream carries telemetry, measurements and events for monitoring, overlay correction and yield analysis.
The shape is: producers on the tool or edge gateway publish to a partitioned log, stream processors consume and enrich, and results land in object storage plus a queryable store. Partitioning is the scaling decision, so I partition by a stable key such as tool_id plus wafer_id, which keeps all measurements for one wafer together and spreads load across tools.
Sizing, with labelled hypothetical figures
Assume 40 tools, each emitting 15 MB/s average after edge compression, so 600 MB/s sustained. A burst of 3x is 1.8 GB/s. If one Kafka partition sustains roughly 50 MB/s of small records in our load test, we need at least 36 partitions for the burst, and I would provision 96 to leave headroom for a broker loss and for consumer rebalancing. Retention math drives cost: 600 MB/s is about 52 TB per day raw, so 7 days is 360 TB before replication. With replication factor 3 that is over 1 PB of disk, which is why the edge gateway compresses and downsamples raw encoder traces, and why after 24 hours data moves to Parquet in object storage at a fraction of the cost.
| Decision | Option A | Option B | When I pick it |
|---|---|---|---|
| Log | Kafka | Cloud Kinesis or Pub/Sub | Kafka when we need long retention, replay and self-hosting in a fab network |
| Processing | Flink streaming | Spark Structured Streaming micro-batch | Flink for sub-second to few-second latency, Spark when the team already runs it and 30 s latency is fine |
| Delivery | At-least-once plus idempotent sink | Transactional exactly-once | Idempotent sink almost always, transactional only where the sink supports it cleanly |
| Schema | Protobuf with a registry | JSON with schemaless consumers | Protobuf for high rate and evolution control, JSON only for low-rate fab events |
Backpressure and failure modes
Producers must be idempotent and must not block the tool. The gateway writes to a local disk buffer first, then publishes. If the log is unavailable, the buffer fills and the gateway sheds low-priority trace data before it sheds metrology results, because overlay data affects the next wafer and raw traces do not.
# Producer: idempotent, keyed, bounded retry (Python, kafka-python style)
producer = KafkaProducer(
bootstrap_servers="kafka:9092",
enable_idempotence=True,
acks="all",
retries=5,
max_in_flight_requests_per_connection=5,
value_serializer=lambda v: v, # bytes from Protobuf
)
producer.send(
"metrology.measurements",
key=f"{tool_id}:{wafer_id}".encode(),
value=record_bytes,
)Consumers commit offsets only after the sink write succeeds. That gives at-least-once delivery, and the sink deduplicates on a natural key such as tool_id, wafer_id, measurement_id. I would not promise end-to-end exactly-once across the log, the processor and the database. I would make the write idempotent and test the replay path.
Three failures I would name in the interview. First, partition skew: one hot wafer or one misbehaving tool sends 10x the average and one partition saturates while others idle. Detection is per-partition bytes and consumer lag, mitigation is key design plus a separate topic for high-volume trace data. Second, poison records: a malformed measurement crashes a consumer in a loop and lag grows for the whole partition. Mitigation is a dead-letter topic after a small retry count, with the original offset and schema version attached. Third, schema evolution: a tool firmware update adds a field and old consumers fail to parse. Mitigation is a registry with backward compatibility checks in CI, and consumers that ignore unknown fields.
Scaling out is then mechanical. Add partitions before lag becomes the bottleneck, add consumer instances up to the partition count, and keep stateful Flink jobs checkpointed to object storage so a rebalance does not lose window state. If a single key ever exceeds one partition, I would split that key with a suffix and accept that ordering is only guaranteed within the sub-key, then rejoin in the processor by wafer_id with a bounded window.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Describe a time you faced a tight deadline. How did you handle it?
Reported in Software Engineer interview at ASML
The 90-second answer
At my previous role I was the software engineer on a motion-control release for a precision stage. Six weeks before the customer acceptance test, the customer pulled the test forward by four weeks because their line slot had moved. The release date became nine working days away, and the scope was still 34 tickets. I did not try to work faster across all 34. I spent the first day building a triage list with the product owner and the test lead, cut the release to the functions the acceptance test actually exercised, and put the rest behind a flag with a dated follow-up ticket. We shipped on day nine, the acceptance test passed, and the deferred work went out in the next release three weeks later without a single escaped defect in the shipped path.
What I clarified first
I asked two questions before accepting the new date. Which date was fixed, the test slot or the internal release milestone? And which requirements were contractual for that test? The test slot was fixed. The internal milestone was not. That distinction mattered because it let us move internal paperwork and a reporting dashboard without moving the customer-facing behaviour.
I also separated scope into three buckets with the test lead, not by effort but by what the test would touch:
| Bucket | Rule | Example from that release |
|---|---|---|
| Must ship | Acceptance test fails without it | Trajectory following fix, interlock handling on stage fault |
| Ship if cheap | Test can pass without it, cost under half a day | Extra diagnostic logging on the fault path |
| Defer with flag | No test dependency, visible to users | Web dashboard export, non-critical alarm banner |
Safety and interlock behaviour stayed in the must-ship bucket even though one item was expensive. Cutting that would have traded a deadline for a hazard, and I said so explicitly in the triage meeting. That is the conversation I would expect at ASML as well, where a machine that moves a wafer stage cannot have its safety path treated as negotiable scope.
The arithmetic that made the cut defensible
We had 210 story points estimated across the 34 tickets. The team had four engineers for nine days, and after stand-ups, code review and test runs the realistic build capacity was about 22 points per engineer for the whole period, so roughly 88 points of new feature work, plus bug fixing. Keeping 210 points was not a stretch goal, it was a queue we could not drain. We cut to 96 points of must-ship work, which still left buffer for the integration failures we knew would appear. I put that calculation in a one-page note to the product owner so the decision was visible and reversible, rather than a silent drop of tickets at the end.
How I handled the pressure in practice
Days one and two were triage and a working agreement. We froze new scope at the end of day two, moved to daily integration builds instead of the usual weekly merge, and gave the test lead a veto on anything entering the release branch after day five. That veto prevented two late additions that would have reopened tested code.
The main failure mode appeared on day four. The shared hardware-in-the-loop rig was booked by another team for two days, and our integration tests started queueing. I detected it from the build dashboard, where queue time went from 20 minutes to over three hours, and I moved the non-hardware unit tests to run on every commit while reserving rig slots in two-hour blocks for the interlock tests only. We lost half a day, not two.
On day seven a trajectory fix regressed a corner case in the fault path. Because we had kept the must-ship list small, I could assign two engineers to it without starving the rest of the release. The fix landed on day eight, we re-ran the full acceptance script on day nine, and the deferred dashboard shipped behind a flag that defaulted to off, so turning it on later did not require a new release branch.
What I took from it
The deadline was met by shrinking the promise early and in writing, not by compressing testing at the end. If I repeated it, I would involve the customer-facing engineer in the day-one triage, because we discovered on day three that one deferred ticket was actually visible in their demo script. We caught it in time, but a 30-minute check on day one would have saved the scramble.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Explain how CNNs work and how to mitigate overfitting?
Reported in ASML Software Engineer Interview Experience & Questions
The 90-second answer
A CNN learns spatial patterns by sliding small learned filters over an image, pooling the strongest responses, and feeding the resulting feature map into a classifier. For ASML work, think wafer or SEM defect images: the network should learn edges and textures that separate a particle or bridge from normal pattern, then generalise to a new wafer, layer, or tool.
Overfitting is when training accuracy keeps climbing while validation accuracy stalls or falls. The gap means the model memorised the training set, including its noise and labelling quirks, instead of the defect signal. I fight it with more representative data first, then regularisation and capacity control, and I always judge it on a held-out set that was never used for training or tuning.
How the convolution actually computes
For one filter, each output pixel is a weighted sum over a small patch of the input, plus a bias, followed by a non-linearity such as ReLU. The same filter weights are reused at every position, which gives translation equivariance and far fewer parameters than a fully connected layer on the same image.
Output size follows (W - K + 2P) / S + 1, where W is input width, K kernel size, P padding, and S stride. A worked trace for a single channel:
| Step | Values | Result |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| Input patch | [[1, 0, 2], [0, 1, 0], [2, 0, 1]] | - |
| Kernel | [[1, -1, 0], [0, 1, -1], [1, 0, -1]] | - |
| Dot product + bias 0 | 1*1 + 0*-1 + 2*0 + 0*0 + 1*1 + 0*-1 + 2*1 + 0*0 + 1*-1 | 3 |
| ReLU | max(0, 3) | 3 |
Stacking layers grows the receptive field. Two 3x3 convolutions see a 5x5 region, three see 7x7, so early layers respond to edges and later layers to shapes made of those edges. Pooling, or strided convolution, reduces spatial size and compute. Global average pooling before the final linear layer collapses each feature map to one number, which cuts parameters sharply compared with flattening a 16x16 map.
# PyTorch, checked against 2.x. Input: (batch, 3, 256, 256)
import torch.nn as nn
class DefectCNN(nn.Module):
def __init__(self, num_classes=4):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
nn.MaxPool2d(2), # 128x128
nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
nn.MaxPool2d(2), # 64x64
nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), # 1x1
)
self.head = nn.Sequential(nn.Dropout(0.3), nn.Linear(128, num_classes))
def forward(self, x):
return self.head(self.features(x).flatten(1))
# Training side: weight decay + early stopping on validation loss
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)Mitigating overfitting, in the order I would apply them
| Lever | What it does | When it helps, and its cost |
|---|---|---|
| More and better data, augmentation | Random crops, flips, small rotations, brightness shifts for SEM images | Usually the largest gain. Augmentation must preserve the label. A flip is safe for most defects, a large rotation may not be for orientation-sensitive patterns. |
| Train / validation / test split by wafer or lot | Prevents near-duplicate images from the same wafer leaking across sets | Critical in fab data. A random image split inflates validation scores because adjacent fields look almost identical. |
| Weight decay, dropout, label smoothing | Penalises large weights, randomly disables units during training, softens hard labels | Weight decay at 1e-2 with AdamW is a reasonable start. Dropout at 0.3 in the head is modest. Too much of either underfits. |
| Early stopping and checkpoint on validation | Stops before the validation curve turns up and restores the best weights | Cheap and effective. Patience of 5 to 10 epochs is typical. It needs a validation set that reflects production mix. |
| Reduce capacity or use transfer learning | Smaller network, or fine-tune a pretrained backbone with a frozen early stack | Best when labelled defects are scarce, which is common. A pretrained model can also import biases from natural images, so I fine-tune and revalidate on fab data. |
| Cross-validation | Trains several folds and averages the estimate | Gives a variance estimate before a release decision. Costs compute, so I use it for model selection, not for every experiment. |
How I would detect it in practice
I plot training and validation loss and accuracy per epoch. Overfitting shows as a widening gap, for example training accuracy at 98% while validation plateaus at 81% and validation loss rises. I also slice validation results by defect class, wafer, and tool. Rare classes often collapse first, which a single aggregate accuracy hides. In a fab setting I would report precision and recall per class, because missing a killer defect and raising a false alarm have very different costs.
Two failure modes deserve a direct mention. Label noise from manual SEM review can be memorised by a large model, so I would audit disagreements between model and labeller rather than trusting either blindly. Distribution shift is the other one: a model tuned on one layer can degrade on the next layer or after a tool change, so I would keep a recent production set aside and re-check performance after any process change, not only at initial release.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Reverse a linked list and output the Fibonacci sequence?
Reported in ASML Senior Software Engineer Interview Questions
The 90-second answer
I would clarify two assumptions first: a singly linked list with a head pointer that can be rewired in place, and Fibonacci meaning the first n terms starting 0, 1. Then I would give the iterative versions of both, because they use O(1) extra space and do not risk stack growth.
For reversal, keep three pointers: prev, curr, and next. At each step save curr->next, point curr back at prev, then advance both. When curr becomes null, prev is the new head. That is O(n) time and O(1) space.
For Fibonacci, keep only the last two values and append each new sum. That is also O(n) time. With uint64_t, the sequence overflows at F(94), so I would reject a request for more than 94 terms instead of silently wrapping around.
// C++17
#include <cstdint>
#include <optional>
#include <vector>
struct Node {
int value;
Node* next;
};
Node* reverse(Node* head) {
Node* prev = nullptr;
while (head != nullptr) {
Node* next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
std::optional<std::vector<std::uint64_t>> fibonacci(std::size_t n) {
if (n > 94) return std::nullopt; // F(93) is the last term that fits in uint64_t
std::vector<std::uint64_t> out;
out.reserve(n);
std::uint64_t a = 0, b = 1;
for (std::size_t i = 0; i < n; ++i) {
out.push_back(a);
std::uint64_t c = a + b;
a = b;
b = c;
}
return out;
}Worked trace: reversal
Input 1 -> 2 -> 3 -> 4 -> null, with prev = null initially:
| Step | curr | next saved | After rewiring | prev |
|---|---|---|---|---|
| 1 | 1 | 2 | 1 -> null | 1 |
| 2 | 2 | 3 | 2 -> 1 -> null | 2 |
| 3 | 3 | 4 | 3 -> 2 -> 1 -> null | 3 |
| 4 | 4 | null | 4 -> 3 -> 2 -> 1 -> null | 4 |
Loop ends with curr = null, return prev = 4. An empty list returns null immediately, and a single node returns itself.
Worked trace: Fibonacci
For n = 10, the loop produces 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. Each iteration does one addition and two assignments, so there is no recursion and no repeated subproblems. A naive recursive version recomputes the same values exponentially often, roughly O(2^n) calls, which is why I would not use it outside a whiteboard.
Trade-offs and failure modes
Recursion reads cleanly for reversal: reverse the rest, then fix the head link. Its cost is call stack depth equal to list length. A list with a million nodes, or a long list processed in a real-time control thread at ASML, can overflow the stack. The iterative form avoids that and makes the pointer updates explicit for review.
Three failures I would name in the interview:
- Lost head. If you advance
headbefore savinghead->next, the remainder of the list is unreachable. The trace above shows whynextmust be saved first. - Cycle in the input. A cyclic list never reaches null, so the loop runs forever and corrupts memory. Production code that accepts lists from another component should run Floyd cycle detection first, or bound the traversal by a known length.
- Integer overflow in Fibonacci. Signed overflow is undefined behaviour in C++, and unsigned overflow wraps silently. Returning
std::nulloptforn > 94, or using a checked add, turns a wrong answer into a visible error.
If the interviewer asks for the nth term only, I would keep the same loop and return a after n steps, still O(n) time and O(1) space. Matrix exponentiation gives O(log n), but it adds code and overflow risk for little gain when n is capped at 93 anyway.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Explain semaphores and mutexes and how they are used in concurrency?
Reported in ASML Senior Software Engineer Interview Questions
The 90-second answer
A mutex protects ownership of one piece of shared state. Only the thread that locked it may unlock it, and the critical section it guards should be short and never block on I/O. A semaphore is a counter with wait and signal operations. It does not have an owner, so any thread can signal it, which makes it suitable for counting resources or events rather than guarding a data structure.
In a machine controller, that distinction matters. I would use a mutex around a shared stage position cache updated by several threads, and a semaphore to limit how many sensor buffers a pool can hand out, or to wake a worker only when work exists.
| Property | Mutex | Semaphore |
|---|---|---|
| --- | --- | --- |
| State | Locked or unlocked | Integer count, binary or counting |
| Unlock rule | Locking thread only | Any thread may signal |
| Typical use | Protect a variable, map, or device register block | Bound a pool, throttle concurrency, signal an event |
| Misuse symptom | Unlock by another thread is undefined behaviour | Extra signals inflate the count and admit too many users |
| Kernel cost | Uncontended case stays in user space, contended case parks on a futex on Linux | Same parking mechanism when the count reaches zero |
Code: each primitive in its proper place
// Checked against C++20, std::counting_semaphore and std::mutex
#include <mutex>
#include <semaphore>
#include <queue>
std::mutex state_mtx;
std::queue<Frame> pending;
std::counting_semaphore<8> buffer_slots{8}; // at most 8 frames in flight
void producer(Frame f) {
buffer_slots.acquire(); // wait if the pool is empty
{
std::lock_guard lock(state_mtx); // only this thread owns the queue here
pending.push(f);
}
work_available.release(); // wake one consumer, whoever it is
}
void consumer() {
work_available.acquire();
Frame f;
{
std::lock_guard lock(state_mtx);
f = pending.front();
pending.pop();
}
process(f);
buffer_slots.release(); // return the slot to the pool
}The mutex guards pending. The semaphore guards capacity. Swapping them breaks the design: a mutex cannot express "eight slots", and a semaphore around pending would let a second thread pop while the first thread is mid update.
Worked trace: bounded buffer with capacity 2
| Step | Action | buffer_slots | work_available | Queue |
|---|---|---|---|---|
| 1 | Init | 2 | 0 | empty |
| 2 | Producer acquires slot, pushes A, releases work | 1 | 1 | A |
| 3 | Producer acquires slot, pushes B, releases work | 0 | 2 | A, B |
| 4 | Producer tries third push | blocks | 2 | A, B |
| 5 | Consumer acquires work, pops A, releases slot | 1 | 1 | B |
| 6 | Producer wakes, pushes C, releases work | 0 | 2 | B, C |
That blocking at step 4 is backpressure. Without the semaphore the producer would allocate unbounded memory during a sensor burst and the consumer would fall behind with no signal to slow down.
Failure modes I would name in the loop
Priority inversion is the one that bites real time systems. A low priority logging thread holds a mutex, a high priority motion thread blocks on it, and a medium priority thread preempts the logger. The high priority thread now waits for the medium one. Linux pthread mutexes can use priority inheritance to raise the holder, but the safer design is to keep the critical section to a few instructions, copy data out, and do formatting or disk I/O after unlocking.
Deadlock comes from lock ordering. Two threads lock the same two mutexes in opposite order and each holds one. The fix is a single global order, documented at the lock site, plus std::scoped_lock when a call genuinely needs both. A semaphore version of the same bug is a lost signal: a thread acquires a slot, throws, and never releases it. RAII guards or a scope based releaser prevent that leak.
I would also say when neither primitive is the answer. A condition variable fits "wait until this predicate holds" better than polling a semaphore, and lock free structures only pay off when profiling shows contention on a hot path, since they trade a clear ownership rule for subtle memory ordering bugs.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Explain C++ fundamentals and how you would design a system in C++?
Reported in ASML Senior Software Engineer Interview Questions
The 90-second answer
C++ earns its place in a lithography machine for three reasons: deterministic cost, zero-cost abstraction, and direct control of memory and threads. I would start from the deadline and the data rate, then choose types that make ownership and timing explicit. For a stage controller or a sensor pipeline, that means fixed-size buffers allocated once, no allocation or locking on the hot path, and a clear split between the real-time thread and everything else.
The fundamentals I lean on daily are RAII, value semantics with move, and templates used sparingly. A resource owns itself in its destructor, so a file descriptor, a lock, or a DMA buffer cannot leak when an exception or an early return happens. std::unique_ptr is the default for exclusive ownership, std::shared_ptr only when ownership is genuinely shared, and raw pointers or std::span for non-owning views. That discipline is what prevents the classic C++ failure in control software: a dangling view into a buffer that a producer thread has already recycled.
Designing the system
Take a concrete case: a wafer stage servo loop running at 1 kHz, reading encoder samples, computing a correction, and writing to a drive. Hypothetical budget: 1 ms period, 200 microseconds allowed for the compute path, jitter under 20 microseconds. I would not start with classes for every concept. I would start with the thread model and the queues.
// C++20, checked against GCC 13. No allocation on the hot path.
#include <array>
#include <cstddef>
#include <span>
template <typename T, std::size_t N>
class SpscRing {
public:
bool push(const T& v) {
const std::size_t head = head_.load(std::memory_order_relaxed);
const std::size_t next = (head + 1) % N;
if (next == tail_.load(std::memory_order_acquire)) return false; // full
buffer_[head] = v;
head_.store(next, std::memory_order_release);
return true;
}
bool pop(T& out) {
const std::size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) return false; // empty
out = buffer_[tail];
tail_.store((tail + 1) % N, std::memory_order_release);
return true;
}
private:
std::array<T, N> buffer_{};
std::atomic<std::size_t> head_{0}, tail_{0};
};The ring is single producer, single consumer. The producer is the I/O thread, the consumer is the control thread. A mutex would work, but it adds a worst case I cannot bound if a lower priority thread holds it. The ring gives me a bounded, lock-free handoff and a clear overflow policy: drop and count, never block the producer.
| Concern | Choice | Why it fits the deadline |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Buffers | Fixed std::array pools, allocated at startup | No heap growth after init, cache behaviour is predictable |
| Handoff | SPSC ring, drop on full | Producer never blocks, overflow is counted and visible |
| Errors | std::expected-style result or error codes on hot path, exceptions at boundaries | Exceptions across a real-time loop make timing analysis painful |
| Configuration | Immutable snapshot published once, read by control thread | No locks or tearing on the hot path |
| Telemetry | Separate ring to a low priority thread | Diagnostics cannot steal time from control |
Worked trace
One cycle, hypothetical figures: encoder read 15 microseconds, ring pop 2 microseconds, correction math 60 microseconds, drive write 10 microseconds. Total 87 microseconds against a 200 microsecond budget, leaving headroom for interrupt latency. If the ring fills, the I/O thread increments a dropped-sample counter and sets a flag the diagnostics thread reports. The control thread keeps running on the last valid sample for a bounded number of cycles, then transitions to a safe state. That behaviour is a design decision I would state up front, because silently blocking or silently extrapolating are both wrong for a stage moving under a lens.
Failure modes I would name in the interview
Priority inversion if a mutex ever appears on the hot path. False sharing if producer and consumer indices sit on the same cache line, which I would fix with alignment padding. A torn read if configuration is updated in place instead of swapped as a snapshot. And unbounded allocation if a std::string or std::vector resize sneaks into the loop through a logging call, which is why logging on the control thread is limited to writing to a preallocated ring.
When I would not use this shape: if the rate is low and the deadline is soft, a simpler design with a mutex and a std::queue is easier to review and maintain. The lock-free ring pays off only when the timing budget is tight enough to justify the extra care. That trade-off, stated with numbers, is usually what the interviewer is listening for.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Given the coordinates of two points, output the distance between them?
Reported in ASML software engineer interview questions · UIRound
The 90-second answer
For points (x1, y1) and (x2, y2) the straight-line distance is the Euclidean distance:
sqrt((x2 - x1)^2 + (y2 - y1)^2)
For (25, -1) and (6, 7): dx = 6 - 25 = -19, dy = 7 - (-1) = 8, so the result is sqrt(361 + 64) = sqrt(425) = 20.6155.... I would return that as a double, not an integer, because the exact value is almost never integral.
In production code I would not write the naive formula directly. I would call std::hypot(dx, dy) in C++, which computes the same result while avoiding intermediate overflow and underflow. That matters at ASML scale, where stage and wafer coordinates can be large integers in nanometres and a squared difference can overflow a 32-bit int long before the final distance does.
Worked trace
| Step | Calculation | Value |
|---|---|---|
| dx | 6 - 25 | -19 |
| dy | 7 - (-1) | 8 |
| dx^2 + dy^2 | 361 + 64 | 425 |
| distance | sqrt(425) | 20.6155 |
Implementation
#include <cmath>
#include <stdexcept>
// C++17. Coordinates as double; use long long inputs if they are integral.
double distance(double x1, double y1, double x2, double y2) {
if (!std::isfinite(x1) || !std::isfinite(y1) ||
!std::isfinite(x2) || !std::isfinite(y2)) {
throw std::invalid_argument("non-finite coordinate");
}
return std::hypot(x2 - x1, y2 - y1);
}std::hypot internally scales by the larger component, so hypot(1e200, 1e200) returns about 1.414e200 instead of overflowing to infinity when the squares are formed, and hypot(1e-200, 1e-200) does not underflow to zero. The naive sqrt(dx*dx + dy*dy) fails both cases.
Assumptions and alternatives
I am assuming a flat Euclidean plane and that the caller wants the straight-line distance. If the points are on a grid and movement is restricted to grid lines, the answer would be Manhattan distance, |dx| + |dy|, which for this example is 27. I would ask which metric the caller needs rather than guess, because the two differ by 30 percent here.
If the caller only needs to compare distances, for example to find the nearest of many points, I would compare squared distances and skip the square root entirely. That is faster and avoids one rounding step. The square root is monotonic, so ordering is preserved.
Failure modes
Integer overflow is the classic trap. With 32-bit ints, dx = 50000 gives dx*dx = 2.5e9, which overflows a signed 32-bit int. Widening to 64-bit before squaring fixes the common case, but hypot on doubles is safer for very large values. Precision loss is the second trap: subtracting two large, nearly equal coordinates, such as 1e9 and 1e9 + 1, can lose the small difference in double precision. Where coordinates come from a stage encoder, I would keep them as integers as long as possible and convert only the differences.
Testing should cover the degenerate cases explicitly: identical points returning 0, points on an axis, negative coordinates as in the example, and the overflow cases above. A test that only checks (25, -1) to (6, 7) would pass an implementation that still overflows on real stage data.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Explain the difference between override and overload?
Reported in ASML software engineer interview questions · UIRound
The 90-second answer
Overloading is resolved by the compiler. Two or more functions share a name in the same scope and differ in parameter types or count. The call site picks one based on the static types of the arguments.
Overriding is resolved at runtime. A derived class provides a function with the same signature as a virtual function in its base. Calls through a base pointer or reference dispatch to the derived version, even though the static type says base.
In C++, which is the language most of our motion and metrology code uses, that distinction decides where a bug shows up. A bad overload is a compile error or a wrong function silently chosen. A bad override compiles cleanly and then calls the base version at runtime, which in a stage controller can mean a safety interlock never runs.
// C++17
#include <iostream>
struct Stage {
virtual void move(double mm) { std::cout << "base move " << mm << "\n"; }
void move(double mm, double speed) { std::cout << "base move+speed\n"; }
};
struct WaferStage : Stage {
// Bring the base overload back into scope. Without this line,
// declaring move(double) below hides Stage::move(double, double)
// and w.move(1.0, 10.0) fails to compile.
using Stage::move;
// Overrides Stage::move(double). The override keyword makes
// a signature mismatch a compile error.
void move(double mm) override { std::cout << "wafer move " << mm << "\n"; }
};
int main() {
WaferStage w;
Stage& s = w;
s.move(1.0); // override: prints wafer move 1
w.move(1.0, 10.0); // overload in base: prints base move+speed
s.move(1.0, 10.0); // overload: prints base move+speed
}Note the last two lines. Stage has no two-argument virtual, so the base overload runs even though the object is a WaferStage. Overloads are not inherited the way people expect. If a derived class declares any function with a given name, it hides every base function with that name unless you add using Stage::move; in the derived class. That hiding rule is a common source of a missing overload after a refactor.
| Overload | Override | |
|---|---|---|
| Decision point | Compile time, from static argument types | Runtime, from dynamic object type |
| Signature | Same name, different parameters in one scope | Same name and same parameters as a base virtual |
| Return type | May differ, but return type alone never overloads | Must match, except covariant return of a pointer or reference to a derived type |
| Keyword | None | override recommended, final to stop further overriding |
| Typical use here | setExposure(int ms) and setExposure(Duration) for distinct units | Hardware abstraction: Stage::move, WaferStage::move, ReticleStage::move behind one interface |
| Failure if wrong | Ambiguous call, or a narrowing conversion picks the wrong overload | Base version runs silently, or object slicing copies only the base part |
Where this bites in practice
First, signature drift. Change move(double) to move(double, bool) in the base and forget the derived class. Without override, the derived function becomes a new overload that hides the base one. Calls through a base reference now hit the base implementation. With override, the compiler rejects it immediately. We require override on every overriding function for that reason.
Second, overloads on units. move(1.0) meaning millimetres in one driver and micrometres in another is not a type difference the compiler can save you from. Both are double. Overloading on double versus int makes it worse, because move(1) picks the int version and move(1.0) picks the double version. For stage code we prefer distinct wrapper types or named parameters over numeric overloads, so a unit error fails to compile.
Third, const and reference qualifiers count. void move(double) and void move(double) const are different functions. A derived const version does not override a non-const base version. Again, override turns that into a compile error instead of a runtime surprise during a wafer run.
Use overloads for genuinely different inputs that share a verb, and keep the set small enough that call sites stay unambiguous. Use overriding when a family of hardware or algorithm variants must be interchangeable through a base interface, which is exactly the pattern behind our sensor and actuator drivers. If a function must be overridden, mark it virtual in the base, mark it override in the derived class, and add a test that calls it through a base reference. That test is the only thing that proves dispatch actually happens.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Print a matrix in spiral order?
Reported in ASML software engineer interview questions · UIRound
The 90-second answer
Assume an m x n matrix, start at the top left, go clockwise, and print each element once. I would keep four bounds, top, bottom, left and right, and peel one layer at a time. Each pass prints the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top, then shrinks all four bounds inward. That is O(mn) time and O(1) extra space if I print as I go, or O(mn) if I collect the result into a list.
# Python 3.11
def spiral(matrix):
if not matrix or not matrix[0]:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
result.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1
return result
print(spiral([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
# [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]Worked trace
For that 3 by 4 matrix, the bounds move as follows:
| Pass | Bounds before | Printed | Bounds after |
|---|---|---|---|
| 1 | top=0 bottom=2 left=0 right=3 | 1 2 3 4, then 8 12, then 11 10 9, then 5 | top=1 bottom=1 left=1 right=2 |
| 2 | top=1 bottom=1 left=1 right=2 | 6 7 | top=2 bottom=0 (loop ends) |
The two if guards before the bottom row and left column matter. Without them a single row or single column gets printed twice. Take [[1, 2, 3]]: after the top row, top becomes 1 and bottom is 0, so the right column loop is empty, and the guards stop the bottom row from reprinting 3 2 1. The same failure hits a 3 by 1 column if the guards are missing.
Alternatives and when I would not use this
| Approach | Extra space | When it wins |
|---|---|---|
| Layer bounds, as above | O(1) to print | Default. No visited set, cache friendly, works for non-square matrices. |
Walk and turn, with a visited set | O(mn) for the set | Easier to extend to irregular shapes or obstacles, but the set costs more than the matrix traversal itself. |
| Recursive peel | O(m + n) stack | Shorter to write, worse for very tall matrices where recursion depth becomes a real limit. |
If the matrix does not fit in memory, for example a wafer map or sensor grid streamed from a file, the layer version still works provided I have random access to rows by index. If rows only arrive once in order, no spiral order can be emitted until the last row is known, because the bottom row of the outer layer is printed third. In that case I would either buffer the whole input or change the traversal to something streamable and say so explicitly.
Edge cases I would name before coding: empty matrix, rows of length zero, 1 by n, m by 1, and ragged input where rows have different lengths. The code above assumes rectangular input. For ragged input I would validate len(row) == len(matrix[0]) up front and raise, rather than letting an index error surface halfway through the output.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Explain how you would handle a situation where a wafer defect is detected late in the manufacturing process?
Reported in Software Engineer interview at ASML
The 90-second answer
First I contain, then I trace, then I fix the software path that let it escape. A late defect is not a process curiosity. It means wafers already moved downstream, possibly into etch, deposition or even a customer shipment, so the software response has to be fast and auditable.
I would assume the defect comes from inline metrology or final inspection after exposure on an ASML scanner, for example a bridging or particle pattern that should have been caught at dose and focus checks. My job as a software engineer is not to redesign the chemistry. It is to make sure the system can hold the right lots, prove which wafers are affected, and feed clean data back to the scanner and the process engineers.
Contain in minutes
The MES and the scanner host software need a hard hold, not an email. When metrology flags a defect signature above threshold, the lot status changes to HOLD, downstream tools reject the lot at load, and the operator sees the reason code on the load port. I would check three things immediately: the hold propagated to every downstream tool, the lot genealogy is complete, and no wafer from that lot already shipped.
Trace with data, not hunches
Late detection usually points to one of four causes: a scanner drift that monitors missed, a metrology sampling plan that looked at too few sites, a tool change such as a new reticle or chamber that was not correlated, or a software bug in timestamping or data alignment. I would pull the full trace for the affected wafers and compare it with clean lots from the same day.
| Signal to pull | What it tells you | Typical source |
|---|---|---|
| Dose, focus, overlay per exposure | Drift or step change at a specific time | Scanner host, wafer stage logs |
| Reticle, chamber, slot, operator | Common tool or material change | MES genealogy |
| Particle counts and defect map | Random particles versus repeating pattern | Inspection tool |
| Metrology sampling plan | Whether the defect site was even measured | Metrology recipe |
A worked trace makes the decision concrete. Hypothetical example: lot L-1042, 25 wafers, defect found on wafer 19 at final inspection. Genealogy shows wafers 1 to 25 all exposed on scanner S-07 between 02:10 and 02:47, same reticle R-3, chamber C-2. Dose logs show a 1.8 percent step at 02:31, exactly before wafer 19. Sibling lots L-1041 and L-1043 on the same scanner in that window get held too, even though their sampled wafers looked clean. That expansion is cheaper than a customer escape.
Find the pattern in code
For the analysis I would write a small reproducible query rather than a spreadsheet export. In Python with the MES export, the check is: group defects by scanner, reticle and hour, and flag any group where the rate jumps.
import pandas as pd
df = pd.read_csv("wafer_trace.csv", parse_dates=["exposure_time"])
df["hour"] = df["exposure_time"].dt.floor("h")
rate = df.groupby(["scanner", "reticle", "hour"])["defect"].mean()
suspects = rate[rate > 0.05] # hypothetical 5% threshold for this line
print(suspects)That output goes to the process and scanner engineers with the raw traces attached. Software owns the pipeline quality: clock synchronisation between scanner, metrology and MES, schema versioning when a new sensor is added, and alerts that fire on rate change instead of only on absolute count.
Fix and prevent recurrence
If the cause is drift, the fix is a tighter interlock in the scanner host: dose deviation beyond a limit for N consecutive exposures stops the lot automatically and requires engineer acknowledgement. If the cause is sampling, the fix is in the metrology recipe and the feedback loop, so a defect signature found late triggers denser sampling on the next lots. If the cause is a software bug, for example misaligned timestamps after a daylight saving change or a dropped sensor stream, I would add a contract test that rejects incomplete traces at ingestion and a dashboard that shows data completeness per tool.
Failure modes I would name in the interview: a false positive hold that stops a good lot, so the disposition path needs a fast release with two-person approval and a full audit trail; incomplete genealogy after a tool was offline, so the hold must default to the wider window when data is missing; and alert fatigue, so thresholds are tuned on historical data and reviewed after every excursion. The goal is a system where the next late defect is held in seconds, traced in hours, and turned into an automatic interlock before the same signature reaches final inspection again.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13How do you prioritize tasks when working on multiple projects with tight deadlines?
Reported in Software Engineer interview at ASML
The 90-second answer
I start by making the deadlines explicit, because at ASML a lot of dates look hard and only some of them are. A customer site acceptance date, a safety interlock fix that blocks a hardware bench, and a feature planned for the next release train do not carry the same cost if they slip by a week. I list every commitment with its hard date, who else depends on it, and what happens if it moves, then I rank by cost of delay divided by effort, not by who shouted loudest or which ticket arrived first.
That ranking only works if I surface conflicts early. If two hard dates collide, I do not quietly drop one. I take both dates, the dependency chain, and two options with dates to my lead and the other project owner, and I get a decision on what slips. In lithography software that matters because verification time often cannot be compressed. A control change for the wafer stage still needs hardware-in-the-loop testing, and skipping that to hit a coding date just moves the failure to integration.
How I rank it in practice
I use a simple score so the trade-off is visible in a stand-up or a planning review:
priority = cost_of_delay_per_week / effort_in_weeks
Cost of delay is not a feeling. It is bench idle time, a blocked team, a missed customer milestone, or a release that cannot ship. Effort includes review and test time, not just coding time. A two-day fix that unblocks three engineers scores higher than a two-week feature that only affects one release.
Worked example from a typical clash, figures illustrative:
| Task | Hard date | Blocked by | Cost if 1 week late | Effort | Score |
|---|---|---|---|---|---|
| Fix interlock fault blocking EUV bench tests | Friday | None, bench reserved Thu-Fri | 3 teams idle, ~15 engineer-days lost | 2 days | 37.5 |
| Deliver recipe parameter UI for next release | In 3 weeks | Bench time after interlock fix | Release scope cut, workaround in spreadsheets | 10 days | 2.5 |
| Update operator documentation | In 3 weeks | UI strings frozen | Minor, operators use current version | 3 days | 1.7 |
The interlock fix goes first even though the UI has a visible release date. It sits on the critical path for the other two. If the bench slot is lost, the UI cannot be validated anyway, so its real deadline moves with it.
Failure modes I watch for
Context switching is the quiet killer. Switching between a safety-critical fix and a UI task costs more than the sum of both, because the mental model for the interlock logic has to be rebuilt each time. I batch the low-priority work into fixed slots and protect deep work blocks for the critical path item.
The second failure mode is the silent slip. An engineer works late for a week, misses a soft date by two days, and nobody re-plans the bench reservation or the downstream test. I flag a risk as soon as the forecast moves, with the new date and what it affects. A lead can accept a two-day slip early. They cannot recover a bench slot that was given away.
The third is treating all deadlines as equal and doing everything at 80 percent. That produces no finished, tested increment. I would rather ship the interlock fix fully tested and move the documentation to the following week, with that trade-off agreed in the open, than deliver three half-tested changes that all fail at integration.
When I escalate, I bring a sentence like this: "The bench fix and the UI validation both need Thursday and Friday. If I keep the bench, the UI slips to the following Monday and we cut the optional parameter screen. If I keep the UI date, we lose the bench slot and both slip. Which date do you want to protect?" That forces a real decision while there is still time to act on it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Describe a time when you had to debug a complex system issue. What steps did you take?
Reported in Software Engineer interview at ASML
The 90-second answer
I would describe a motion control system I debugged where a machine aborted intermittently during a specific operating mode, with no single log line identifying the cause. The example below is illustrative, and the figures are hypothetical, but the method is what I would walk through.
My first step was to stop guessing and collect synchronized evidence. I froze the configuration, pulled traces from the motion controller, the task sequencer, and the safety monitor for the same run, and aligned them on a common timestamp. That showed position error rising well before the abort, while the sequencer still reported nominal. I then bisected by subsystem. I replayed the recorded motion profile on a test rig without the sequencer attached. The error reproduced, which cleared the sequencer and pointed at the servo loop and its feedback path.
The fix was a tuning change for that one mode, plus a regression test that replays the recorded profile. I verified it by replaying the profile repeatedly and then running the full sequence, checking that error stayed inside budget in every mode, not just the failing one.
What the trace showed in the illustrative example
Assume a 4 kHz position loop and a hypothetical error budget of 3 nm for this mode. The table is a worked example, not data from a named product.
| Time (ms, aligned) | Motion controller | Task sequencer | Safety monitor |
|---|---|---|---|
| -400 | Following error 1.8 nm | Task in progress | Nominal |
| -200 | Following error 6.4 nm, rising | Task in progress | Nominal |
| -40 | Following error 11.9 nm | Task in progress | Nominal |
| 0 | Abort threshold crossed | Abort requested | Fault latched |
Two details mattered. First, the error only appeared in the high acceleration mode, so a short test in the low mode passed and hid the fault. Second, the sequencer only sampled motion state at task start, so its logs looked clean. Trusting either source alone would have sent me to the wrong subsystem.
How I isolated it
I used a small script to align the traces, because the sources used different clocks and formats. Eyeballing them had already proved unreliable in earlier work.
# Python 3, illustrative snippet for the example above
import csv
from collections import defaultdict
rows = defaultdict(list)
with open("aligned_trace.csv") as f:
for r in csv.DictReader(f):
rows[r["source"]].append((int(r["t_ms"]), float(r["value"])))
for t, err in rows["stage_nm"]:
if abs(err) > 3.0: # hypothetical budget for this mode
print(f"first breach at {t} ms: {err} nm")
breakThat gave me a concrete first breach time to compare against sequencer events, instead of a vague sense that the traces looked off.
Alternatives I ruled out, and how
Timing jitter was plausible because the abort was intermittent. I checked heartbeat and packet counters for the same window and found no drops, and the error rose smoothly rather than stepping, which fits a tuning problem better than a lost sample. A sensor fault was also plausible, so I swapped the feedback sensor and cable between two axes. The error stayed with the axis and mode, not with the sensor, which ruled that out.
Fix, verification, and follow up
In the example, the tuning for that mode had been carried over from a different load configuration. Retuning the gain and adding a filter for the resonance visible in the error spectrum brought peak error from about 12 nm to under 2 nm in replay. Verification was not a single pass. I replayed the profile 50 times, then ran the full sequence, and confirmed no aborts and no budget breaches in any mode.
I also pushed two changes to prevent a repeat. The sequencer now logs following error continuously during the task instead of only at task start, so a precursor is visible next time. And the regression suite gained a recorded profile replay for each motion mode, because coverage had only exercised the low mode that never failed. The debugging steps found the cause, but the logging and test changes are what stop the same class of fault from hiding again.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15What is Infrastructure as Code and why does it matter in practice?
Reported in ASML Software Engineer Interview — Technical | Screna AI
The 90-second answer
Infrastructure as Code means describing servers, networks, clusters and their configuration in version-controlled files, then applying those files with a tool to create or change the real environment. The file is the source of truth. A human does not click through a console or run a one-off script on a machine and hope it matches last time.
In practice at a company like ASML, that matters for three concrete reasons. First, reproducibility. A lithography control test bench, a simulation cluster for optics modelling, and a CI runner pool are expensive and scarce. If an engineer can recreate the same bench from a commit, a failed qualification can be rerun instead of debated. Second, review. A change to a firewall rule or a Kubernetes limit becomes a pull request with a diff, a reviewer and a rollback plan. Third, audit. When a machine ships to a customer fab, you need to show exactly what software and configuration produced a test result. "Someone set it up by hand in 2023" does not survive that.
How it works
Most tools are declarative. You state the desired end state, the tool computes the difference from the current state and applies it. Terraform, Pulumi and AWS CDK work this way for cloud resources. Ansible and Chef are closer to imperative tasks, useful for configuring inside a machine after it exists. Kubernetes YAML is declarative for workloads.
A minimal Terraform example for a compute node pool used for simulation jobs:
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
}
resource "aws_eks_node_group" "sim" {
cluster_name = aws_eks_cluster.main.name
node_group_name = "sim-compute"
node_role_arn = aws_iam_role.eks_nodes.arn
subnet_ids = var.private_subnet_ids
instance_types = ["c6i.4xlarge"]
scaling_config {
desired_size = 8
min_size = 2
max_size = 32
}
labels = {
workload = "optics-simulation"
managed_by = "terraform"
}
}Apply is idempotent in intent. Running it twice with no file change should produce no changes. That property is what makes it safe to run in CI on every merge.
Why it matters in practice, with numbers
Manual setup of a test cluster typically takes a skilled engineer 2 to 3 days, and the result depends on who did it. With IaC, first creation is about 20 minutes of apply time, and a rebuild after a bad experiment is the same command. The saving is not just time. It is that the second environment is identical, so a bug reproduced on one bench can be reproduced on another.
Drift is the failure mode people underestimate. Someone edits a security group in the console to unblock a test. The file and reality diverge. The next apply either overwrites the manual fix, which breaks their test, or, if the tool is run in plan-only mode, nobody notices until an audit. A nightly terraform plan in CI catches this. In a worked trace: Monday 09:00 plan shows 0 changes. Tuesday 14:00 an engineer opens port 22 from 0.0.0.0/0 in the console. Wednesday 02:00 the nightly plan reports 1 change, the security group rule. The alert fires before that rule is forgotten.
| Approach | Change review | Repeatability | Main risk |
|---|---|---|---|
| Manual console clicks | None | Low, depends on operator | Undocumented drift |
| Shell scripts run by hand | Partial, script is reviewed | Medium, order and host state matter | Partial failure leaves half-configured host |
| Declarative IaC with remote state | Diff in pull request | High, same file produces same result | State file corruption, provider version changes |
Trade-offs and failure modes
IaC is not free. You now own a state file, provider upgrades and module boundaries. A corrupted or locked Terraform state can block all applies. Pin provider versions, store state in a remote backend with locking, and keep state per environment rather than one file for everything. For an S3 backend, current Terraform versions support S3 native locking with use_lockfile = true, which supersedes the older DynamoDB locking table. If you use the hosted service, it is now HCP Terraform, formerly Terraform Cloud.
Partial applies are real. If apply creates a VPC but fails on the node group, the next apply must resume cleanly. That is why small, well-scoped modules beat one 5,000-line file. Secrets are another trap. Never put credentials in the code file. Use a secrets manager and pass references, because the code lives in Git for years.
When not to use it: a one-off experiment on a laptop, or a machine where the vendor only supports manual configuration through a certified tool. Forcing IaC there adds ceremony without benefit. For anything that must be rebuilt, audited or shared across a team, which describes most of ASML's test and simulation infrastructure, manual setup is the riskier choice.
A strong closing line in an interview: IaC does not make infrastructure automatic. It makes changes reviewable, repeatable and reversible, and that is what lets a team move fast without losing track of what is actually running.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16How does Terraform manage state, and what problems can come up with it in a team environment?
Reported in ASML Software Engineer Interview — Technical | Screna AI
The 90-second answer
Terraform keeps a JSON state file that maps configuration addresses, such as aws_instance.runner, to the real resource IDs returned by the provider API. It also records attributes, dependencies, a serial that increments on every write, and a lineage UUID identifying the state. On plan, Terraform reads the configuration, refreshes the resources recorded in state against the live API, and diffs the three. On apply, it creates, updates or deletes in dependency order and writes state as it goes, so a crash mid-apply leaves state matching what was actually created, not what was intended.
Local state works for one person. In a team it fails in predictable ways, which is why production teams move state to a remote backend with locking and versioning.
Remote backend and locking
A backend moves the file off the laptop and serialises writes. With S3, for example:
terraform {
required_version = "~> 1.10"
backend "s3" {
bucket = "asml-ci-tfstate"
key = "runners/eu-west/terraform.tfstate"
region = "eu-west-1"
encrypt = true
use_lockfile = true
}
}use_lockfile (Terraform 1.10 and later) creates a .tflock object next to the state. A second apply fails fast with a lock error instead of overwriting the first run. S3 versioning keeps previous state versions if a bad apply lands. Azure Blob, GCS and Terraform Cloud offer the same pattern, with Terraform Cloud adding run queues and policy checks.
Where teams get hurt
| Problem | What happens | How you catch it and fix it |
|---|---|---|
| --- | --- | --- |
| Concurrent applies | Two engineers apply from the same base state. The second overwrites the first, orphaning resources it created. | Locking prevents this. If someone force-unlocks, compare terraform state list with the cloud console before the next apply. |
| Stale or lost state | State is deleted, copied to a new backend, or restored from an old version. Terraform plans to recreate everything, or misses resources it no longer manages. | Keep versioning on, restrict who can delete state objects, and test a restore. Use terraform import or terraform state pull to reconcile by hand. |
| Drift | Someone edits a security group or runner image in the console. The next plan shows a diff nobody asked for. | Run terraform plan -detailed-exitcode on a schedule in CI. Exit code 2 means drift. Decide whether to reapply the configuration or import the change into it. |
| Secrets in plaintext | State stores every attribute returned by the provider, including passwords, tokens and private keys. Anyone who can read the bucket can read them. | Encrypt at rest, apply tight IAM to the state bucket, and treat state access like production secret access. Rotate anything that leaked into a commit. |
| Partial apply | Apply fails halfway. Some resources exist and are recorded in state, but dependents were never created. | Re-run apply. Terraform resumes from state. For a resource that is genuinely broken, terraform apply -replace=aws_instance.runner forces recreation. The older terraform taint command is deprecated in favour of -replace, so do not edit state by hand to mark it. |
| Refactors | Renaming a resource or moving it into a module changes its address. Terraform plans to destroy the old one and create a new one. | Use moved blocks (Terraform 1.1 and later) or terraform state mv before apply. Review the plan for unexpected deletes. |
| State growth | One state for a whole test cluster grows large and every plan touches everything. Workspaces multiply this, one state per workspace with no sharing. | Split by lifecycle and blast radius, not by team. One state per environment or cluster, with shared modules for the common parts. |
What I would set up for a shared build or test cluster
One state per environment, in a versioned, encrypted backend with locking, access limited to the CI identity and a break-glass role. Pin Terraform and provider versions in the repo, because a provider upgrade can change how attributes are stored and produce a large spurious diff. Run plan on every pull request and post the output, so reviewers see deletes before merge. Apply only from CI, never from a laptop, which removes most lock contention and stale-state errors. Keep modules small enough that a failed apply affects one cluster, not every runner.
The failure mode I watch most is a confident apply from an old state. Refresh on plan re-reads the live API for resources already recorded in the state in the backend in use, so it will surface drift on those resources. It will not surface resources created outside Terraform that were never imported, and it does nothing if the team is pointing at a different backend. That is a process problem Terraform cannot solve for you.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17How do you handle secrets in an IaC setup without putting them in the repo?
Reported in ASML Software Engineer Interview — Technical | Screna AI
The 90-second answer
I keep the secret itself out of the repo, out of the plan, and out of long-lived credentials. The repo holds a reference, for example a Vault path or a Key Vault name, plus the policy that says which workload may read it. At apply time the infrastructure gets a short-lived credential through workload identity, fetches the secret from the manager, and injects it only into the target resource. Nothing plaintext lands in a .tfvars, a YAML file, or a CI variable that persists.
For ASML I would assume a split estate. Corporate IT may use a cloud vault, but fab and machine-control networks are segmented and often air-gapped, so I would not design a deploy that depends on reaching a public cloud endpoint from a cleanroom controller. An on-prem HashiCorp Vault or an HSM-backed PKI in the fab network, with the same reference pattern, works in both places.
How it works in Terraform
# No secret value in the repo. Only the path and the identity.
data "vault_generic_secret" "db" {
path = "fab/prod/postgres/app"
}
resource "kubernetes_secret" "app" {
metadata {
name = "app-db"
namespace = "prod"
}
type = "Opaque"
data = {
# Marked sensitive by the provider. Never printed in plan output.
password = data.vault_generic_secret.db.data["password"]
}
}The CI job authenticates to Vault with OIDC or a Kubernetes service account, not a stored token. Vault issues a token for, say, 1 hour, scoped to that one path. The apply runs, the secret is written to the cluster, and the token expires. If the job is rerun next week it gets a fresh token. There is no credential to steal from the repo or from a long-lived CI secret.
Trade-offs I would name in the interview
| Approach | Where the secret lives | Main risk |
|---|---|---|
| Secret manager reference, as above | Vault, Key Vault, Secrets Manager | Manager outage blocks deploys, state file still holds the value |
| Runtime injection only, for example External Secrets Operator | Vault or cloud vault | IaC cannot provision resources that need the value at create time, such as a database user |
| Sealed or encrypted file in the repo | Repo, encrypted with a KMS key | Key management moves the problem, rotation is manual, reviewers cannot audit content |
I use the first pattern for provisioning and the second for application runtime where possible. A database password needed to create the database user has to exist at apply time. An application password that only the pod needs should be fetched by the pod at startup, so a Terraform state leak does not hand over the runtime credential.
Failure modes and how I catch them
Terraform state is the trap most teams miss. Even with a sensitive variable, the applied value is stored in state. I encrypt the S3 or on-prem backend, restrict state access to the deploy identity, and treat state as a secret store in the audit. I also run gitleaks or an equivalent scanner in pre-commit and in CI, and I fail the build if a plan output contains a value matching a known secret pattern.
Rotation is the second trap. A 24-hour static password rotated in Vault will break any client still holding the old one. For databases and service accounts I prefer dynamic secrets with a 1-hour lease, or dual-password rotation where the new password is issued first, clients pick it up, and the old one is revoked after a grace period. For long-lived fab equipment that cannot reconnect on its own, I would schedule rotation with the equipment owner and verify the reconnect path in a test cell before touching production.
The third trap is overprivilege. A deploy identity that can read fab/* can read every secret in the fab. I scope the Vault policy to one path per service, log every read, and alert on reads outside a deploy window. If Vault is unreachable, the deploy fails closed. I would rather have a failed apply than a fallback that reads a cached plaintext file.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18How do you detect and handle data skew in a Spark job?
Reported in ASML Software Engineer Interview — Technical | Screna AI
The 90-second answer
Data skew means a few keys or partitions hold a disproportionate share of the rows, so a handful of tasks run for minutes while the rest finish in seconds. I detect it from the stage, not from the job duration alone: in the Spark UI I compare task duration, input size and shuffle read/write per partition, and I look for spill, long GC and retried tasks on the same partition. A healthy stage has a tight spread. A skewed stage has one or two tasks 10 to 100 times the median.
Then I fix the operation that is skewed, which is usually a shuffle join or a groupBy. The fixes are salting the hot key, splitting the hot key out and handling it separately, broadcasting the small side of a join, or letting Adaptive Query Execution split the skewed partition. I pick based on whether the skew is in the key distribution or in the input partitioning.
Detection with real numbers
Suppose a job joins wafer lot measurements to tool sensor events on lot_id. The Spark UI stage shows 200 tasks, median task time 8 s, one task at 11 minutes, shuffle read 38 GB on that task against a 400 MB median, and spark.sql.adaptive.skewJoin.enabled has not split it. That pattern points at a hot lot_id, not at a slow executor. I confirm by counting keys before the shuffle on a sample, or by reading the event log:
# PySpark 3.5, run on a 1% sample to find hot keys before the full shuffle
df.sample(fraction=0.01, seed=42).groupBy("lot_id").count() \
.orderBy("count", ascending=False).show(20)If the top key is 35% of rows, salting or splitting that key will help. If counts are even but one partition is still huge, the input files are uneven and repartition on the join key, or fixing the upstream writer, is the fix.
| Signal in Spark UI / event log | Likely cause | First fix |
|---|---|---|
| One task long, shuffle read huge, others idle | Hot join key | AQE skew split, or salt both sides |
| One task long, input size huge, shuffle small | Uneven input files | Repartition, fix upstream partitioning |
| All tasks slow, spill to disk, GC high | Aggregation too large per key | Two-phase aggregation, increase partitions |
| Stage retries same partition repeatedly | Executor OOM or node loss on hot partition | Reduce per-task data, raise memory, split hot key |
Handling a skewed join
For a join where one lot_id dominates, I first enable AQE skew handling and check it actually fired in the query plan:
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.factor", "5")AQE will split the skewed partition of the large side and replicate the matching rows from the small side. That works when the small side has few rows for the hot key. If the small side also has millions of rows for that key, AQE cannot save it and I salt manually.
N = 32
left = left.withColumn("salt", (rand() * N).cast("int"))
right = right.withColumn("salt", (rand() * N).cast("int"))
joined = left.join(right, ["lot_id", "salt"], "inner")Salting spreads the hot key across 32 sub-keys, so 32 tasks share the work. The cost is that both sides must be salted and the join output grows, because each left row now matches only the right rows with the same salt. For a groupBy the pattern is different: aggregate by (key, salt) first, then aggregate by key alone. That two-phase aggregation keeps the shuffle smaller than salting a join.
Handling a skewed aggregation and when to split the key out
For groupBy("lot_id").agg(...) where one lot has 40% of sensor rows, I use two-phase aggregation: groupBy("lot_id", "salt").agg(...) then groupBy("lot_id").agg(...) over the partial results. If the aggregation is a simple count or sum this is clean. If it is a percentile or a collect_list, the second phase still has to gather all values for the hot key, so salting alone does not fix it. In that case I split the hot key out, process it with a dedicated higher-partition job, and union the result back. That costs an extra pass over the hot data, which is worth it when the alternative is one task holding the whole key in memory and spilling or failing.
I verify the fix by rerunning and checking that the max task time falls close to the median, that no partition spills, and that row counts before and after match. A fix that only shortens the job but changes the count for the hot key is a bug, not an optimisation.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Tell me about a difficult project where you had to work across multiple teams or roles?
Reported in ASML Software Engineer Interview — Onsite | Screna AI
The 90-second answer
I will use a project from my last role: adding closed-loop dose control to a wafer inspection tool. The algorithm was mine, but it only worked if three other teams changed their parts on the same release date. Hardware owned the light source timing, metrology owned the reference wafer measurements, and field service owned the calibration procedure customers ran at 2 a.m. My job became less about the code and more about making the interfaces between those teams explicit early enough that we could test them.
The situation: dose drift of about 1.5% across a wafer was pushing overlay error outside spec on the customer's line. The fix needed a new measurement every 50 wafers, a controller update within one wafer cycle, and a fallback if the measurement was stale. Each team had a different definition of "current." Hardware meant the last source pulse. Metrology meant the last completed scan, which could be 90 seconds old. Service meant the last operator-confirmed calibration.
That mismatch was the real bug. We spent the first three weeks arguing about whose timestamp to trust while the algorithm sat idle.
What I did
I proposed we stop debating and write down one contract per interface, with units, freshness, and failure behaviour. I owned the controller interface, so I drafted it first and put my name on the failure cases.
The contract table we signed off on looked like this. Figures are hypothetical and labelled as such for illustration, representative of the scale we were dealing with:
| Interface | Owner | Freshness rule | On failure |
|---|---|---|---|
| Dose sample feed | Metrology | Discard if older than 120 s | Controller holds last value, logs stale_sample |
| Source timing pulse | Hardware | Must arrive within 5 ms of wafer start | Abort correction for that wafer, do not guess |
| Calibration state | Service | Operator confirmation expires after 24 h | Block closed loop, allow fixed dose mode |
Two decisions mattered. First, we built a simulator for the metrology feed before metrology finished their side. I wrote a Python stub that replayed recorded scans with configurable delay, so controls and I could test the stale-sample path in week four instead of week ten. Second, we agreed the controller would never extrapolate. If the sample was stale, it held the last correction and flagged it. Extrapolating felt smarter, but it hid a failing sensor from the customer.
The conflict
Hardware wanted to ship on the existing timing board. Metrology wanted a new scan pattern that added 8 seconds per lot. Service wanted a manual step because their customers trusted a human check. We could not have all three on the original date.
I ran a short trade-off session with one page: error budget on the left, schedule on the right. In simulation, the new scan pattern cut dose error from 1.5% to 0.4% if it ran every 50 wafers, but only to 0.7% if it ran every 200 wafers. The second option still met spec and cost 2 seconds per lot instead of 8. Hardware kept their board. Service kept a manual confirmation, but only at lot start instead of every calibration. Everyone gave up something they preferred, and the numbers made the compromise defensible in the design review.
Result and what I would repeat
We shipped six weeks after the original target date, once the scope was renegotiated around the every-200-wafers scan. On the first customer install, the controller rejected 3 stale samples in the first shift and held dose instead of drifting. That log entry is what convinced the customer to keep closed loop enabled.
If I faced the same setup again, I would write the freshness and failure rows before writing any algorithm code. In my case the algorithm took three weeks. The interface contract took one week to draft and saved roughly six weeks of rework across three teams. That is the pattern I now look for: when teams disagree about timing, units, or who decides on failure, the code is not the hard part.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Tell me about a time you took ownership of a problem that wasn't formally assigned to you?
Reported in ASML Software Engineer Interview — Onsite | Screna AI
The 90-second answer
At my previous role I was a backend engineer on the software that collects metrology data from production tools. My ticket queue was feature work for a dashboard. I kept seeing the same alert in the team channel: the ingestion service timed out for 30 to 90 seconds every weekday around 09:00, and operators re-ran the export by hand.
Nobody owned it. The platform team thought it was an application bug, and my team thought it was infrastructure. I decided to treat it as mine for one week, with a clear exit condition: either I found a root cause and a fix I could land, or I wrote up evidence good enough for the owning team to pick it up without me.
I started by reproducing the pattern instead of guessing. I pulled the service logs for the previous four weeks and aligned them with the deploy history and the database metrics. The timeouts correlated with a scheduled reporting job that ran at 09:00 and opened 180 database connections at once. Our pool was capped at 20. The reporting job was not malicious, it was just doing a full scan on a table that had grown from 40 million to 900 million rows, and it held connections while it waited on disk.
I prototyped a fix in a branch: cap the reporting job to 5 connections, move it to a read replica, and add a timeout so it failed fast instead of queueing behind interactive traffic. I ran it against a production-like snapshot for three days. Interactive p99 went from 180 ms to 42 ms during the 09:00 window, and the reporting job finished in 11 minutes instead of timing out. I then took the data to both teams, not just the code. The platform team agreed to raise the replica, my team agreed to own the job config, and I stayed on call for the first two runs after rollout.
The result held for six weeks. Manual re-exports dropped from about 15 a week to zero, and we deleted the alert. What I took from it: ownership meant producing evidence the actual owners could act on, not just fixing a symptom in my own code.
What I did differently from just filing a ticket
Filing a ticket would have been defensible. It also would have left the problem in the gap between two teams for another month. Instead I time-boxed the investigation, kept my assigned work moving, and made the scope explicit to my manager on day one. That mattered at ASML scale too, where a problem can sit between a software team, a hardware team, and a customer support team. Saying "I will spend two days gathering evidence, then hand over or fix" is easier to approve than an open-ended rescue.
Worked trace
| Day | Action | Evidence produced |
|---|---|---|
| 1 | Told manager the scope and exit condition, pulled 4 weeks of logs | Timeout window matched 09:00 reporting job in 19 of 20 cases |
| 2 | Checked pool metrics and table growth | Pool saturated at 20 connections, reporting job requested 180 |
| 3 | Ran prototype against a snapshot | Interactive p99 180 ms to 42 ms, job completed in 11 minutes |
| 4 | Wrote one-page summary with graphs and rollback plan | Both teams signed off on replica and config change |
| 5 to 10 | Supported rollout, stayed on call for first runs | Zero manual re-exports, alert removed after 6 weeks |
Failure modes I checked
The obvious risk was that I would fix the wrong layer. If the bottleneck had been disk throughput on the primary, moving the job to a replica would have helped the service but left the job slow and expensive. That is why I measured the snapshot first. A second risk was social: two teams could each assume the other had approved the change. The written summary, with named owners for the replica and the config, prevented that. A third risk was scope creep. I did not rewrite the reporting job. I capped its connections and moved it, which was reversible in one config change.
If I hit the same situation here, I would follow the same pattern: reproduce with data, prototype small, and hand over with an owner and a rollback plan. Ownership is not taking over someone else's roadmap. It is closing the gap that the roadmap left open.
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: