
Recall first from Core questions, whiteboarding, and system design
- Process startup, local readiness, and cloud delivery are separate milestones.
- A committed SQLite row and an MQTT PUBACK establish guarantees at different boundaries.
- Stable record IDs let the cloud deduplicate retries after an interrupted upload.
Write code you can verify under a timer
4 min readTalking about design leads to writing code and justifying choices; this lesson covers live coding and the why questions.
A pipe can report a hangup while it still contains unread bytes. If your event loop closes the descriptor as soon as it sees the hangup, it can discard the writer's final data. The epoll_ctl(2) manual documents this behavior under EPOLLHUP: reads return 0 only after all outstanding data in the channel has been consumed. See also epoll(7). It gives you a small interview problem with an observable result. Send a known byte sequence, close the writer, and account for every byte before the reader exits.
For a CMake cross-build, establish the target user-space ABI first. A Raspberry Pi 4 or 5 running a 64-bit Linux user space is a reasonable AArch64 target for this prompt. Say which compiler and target development files you have. For a minimal project, put cmake_minimum_required(VERSION 3.16), project(gateway LANGUAGES C), and add_executable(gateway main.c) in CMakeLists.txt. Supply your own main.c. Keep the target settings in aarch64.cmake.
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
With the Ubuntu cross compiler and its target C development files available, configure into a fresh build directory and inspect the resulting executable.
cmake -S . -B build-arm64 -DCMAKE_TOOLCHAIN_FILE="$PWD/aarch64.cmake" &&
cmake --build build-arm64 &&
file build-arm64/gateway &&
readelf -h build-arm64/gateway
The ELF header should identify AArch64. That verifies the architecture. Running on the target also requires a compatible runtime and, for a dynamically linked executable, its loader and shared libraries. If the prompt supplies a board SDK, use its compiler and target sysroot. When writing your own SDK toolchain file, set CMAKE_SYSROOT to the supplied sysroot and use CMake's root-path modes so library, include, and package searches use target roots while build tools are found on the host. Keep native and cross-build directories separate because CMake caches compiler settings.
For an epoll event loop, start with a nonblocking pipe read end. pipe2 with O_NONBLOCK | O_CLOEXEC creates both ends with those flags and needs _GNU_SOURCE for its glibc declaration. Create the epoll instance with epoll_create1(EPOLL_CLOEXEC), then register the read end with epoll_ctl and EPOLL_CTL_ADD. Request EPOLLIN and use the default level-triggered mode. Store the read descriptor in epoll_event.data.fd so each returned event identifies its source.
Check epoll_wait before iterating over its results. Retry an interruption reported as EINTR and handle other failures. On EPOLLIN or EPOLLHUP for the pipe, read and process positive byte counts. Retry an interrupted read. Stop draining on EAGAIN and return to waiting. A return of zero marks end-of-input after the pipe has drained. Treat other read errors as failures. Check setup calls and release every descriptor you own on exit. For a single-pipe demonstration, prefill the pipe with a small payload using checked writes and close the write end before waiting. That makes the data-plus-hangup case reproducible without a second thread.
For a finite-state machine, define the legal transitions before writing the dispatcher. A reconnect controller can start in IDLE. START moves it to CONNECTING and requests a connection attempt. CONNECTED moves it to ONLINE. FAILED while connecting and DISCONNECTED while online both move it to BACKOFF and request a retry timer. TIMEOUT in BACKOFF moves it to CONNECTING and requests another attempt. An event with no defined transition leaves the state unchanged and requests no action.
Use enums for states, events, and actions. A function can return the next state and requested action as a struct. Keep I/O outside that function so a test can send events in a fixed order and check both fields. An early TIMEOUT in ONLINE should leave the controller online. Then send DISCONNECTED followed by TIMEOUT and check that the attempt is requested only on the transition out of BACKOFF. If asked about asynchronous callbacks, explain how you would identify which attempt produced a callback before accepting it.
Show where database and network operations finish
3 min readFor a SQLite transaction, use a small inventory transfer with an invariant you can query. Start with two rows in stock(sku TEXT PRIMARY KEY, qty INTEGER NOT NULL CHECK(qty >= 0)). Use the distinct, existing keys source and destination and seed them with quantities 2 and 0. The following statements move one unit. Execute them one at a time so the caller can check success and inspect the debit before issuing the credit.
BEGIN IMMEDIATE;
UPDATE stock SET qty = qty - 1 WHERE sku = 'source' AND qty >= 1;
UPDATE stock SET qty = qty + 1 WHERE sku = 'destination';
COMMIT;
BEGIN IMMEDIATE starts a write transaction up front and can fail if another connection already holds a write transaction. After each update, require exactly one changed row. In the CLI, query SELECT changes(); immediately after each update. In C, prepare and bind the statements, check for SQLITE_DONE from sqlite3_step, and inspect sqlite3_changes on the connection before any other write. An update can execute successfully and change zero rows. Here that means the transfer must stop.
Commit only after both updates pass. Check the commit result before reporting success. On an error after the transaction starts, roll back if it remains active. Some errors can already have ended the transaction, which a C caller can check with sqlite3_get_autocommit. In the CLI, inject a failure by crediting a missing key, observe zero changed rows, and issue ROLLBACK explicitly. Query both quantities afterwards. That catches an implementation that preserved the total on a successful transfer but left a debit behind on failure.
For an MQTT client, give the interview prompt a concrete finish condition. For example, connect to a local test broker, publish one telemetry message at QoS 1, and exit after the broker acknowledges it or a deadline expires. With libmosquitto, initialise the library, create a client, and register connect and publish callbacks. Check the return from the connection call and drive network processing with mosquitto_loop using a finite wait. Publish only after the connect callback reports that the broker accepted the connection.
Check mosquitto_publish and record the message ID it returns through its output argument. A successful call means the library accepted the publish request. Keep servicing the network until the publish callback reports completion for that message ID. For this local QoS 1 test, completion corresponds to the broker's PUBACK. If the connection drops or the deadline expires before the callback, report the delivery outcome as unknown once the publish has been queued. Release client resources on exit. For a longer-lived client, explain how reconnect delays and a bounded queue keep an outage from causing rapid retries or unbounded memory use.
Answer why with a guarantee and a boundary
3 min readStart with the product requirement. Name the mechanism you would choose, give the guarantee in one sentence, and name a failure or cost the design must account for. If the interviewer changes a constraint, say how it affects your choice. The same format works for storage, messaging, communications, and updates.
Why use an atomic write for configuration? A reader opening the config path should see a complete old file or a complete new file. Write the full replacement to a temporary file in the same directory, checking for short writes and errors. Sync the temporary file with fsync, close it and check the result, then rename it over the live path. Sync the parent directory to persist the name change. The rename provides atomic replacement at the pathname. An already-open descriptor still refers to the old file. The sync calls address durability and depend on a filesystem and storage stack that honor them. If syncing the directory fails after the rename, the new file may already be visible and its persistence is unconfirmed.
Why choose one MQTT QoS level over another? QoS 0 gives at-most-once delivery for that protocol exchange and permits loss. It suits a stream where the next sample can replace the missing one. QoS 1 gives at-least-once delivery under the protocol's delivery conditions, so retransmission can yield duplicates. For an event that must be processed once, give it a stable ID and record that ID in the same transaction as the application change when both live in the same database. QoS 2 adds a handshake to provide exactly-once delivery within its protocol exchange. It costs additional messages and state. Publisher-to-broker and broker-to-subscriber exchanges have their own QoS, and application effects need their own guarantees across failures.
Why use mutual TLS? In a typical server-authenticated TLS deployment, the device validates the server's certificate and identity, and TLS protects traffic in transit. Mutual TLS also authenticates the device to the server using a client certificate and proof of possession of its private key. Choose it when the service needs a cryptographic identity for each device and the fleet can provision, protect, and rotate those credentials. Then apply authorization to that identity. A valid device certificate should lead to a specific set of allowed actions or topics.
Why D-Bus instead of a socket protocol? For a local service with named peers, typed methods, and change notifications, D-Bus gives clients a common interface and provides bus policy controls. For two local processes exchanging a high-rate byte stream, a Unix-domain stream socket can be a better fit if the application can define framing, peer checks, and backpressure. A stream read can contain a partial message or several messages. If the product needs both styles, explain which traffic belongs on each interface and how you would measure the throughput or latency that drove the decision.
Why containers or A/B OTA? A container packages and runs an application with its user-space dependencies under the host kernel. Updating the image can replace that application independently. A/B OTA addresses bootable system updates. Write the new image to the inactive slot, boot it provisionally, and mark it good after health checks pass. A boot policy can then return to the previous slot if the new one fails. Use both when application releases and platform releases have different schedules. State what happens to shared persistent data. Booting the old slot can still fail at the application level if a migration made that data incompatible.
After you explain a choice, name one observation that would verify it. Debugging and security scenarios follows by asking how you would investigate a failure or a security concern using evidence from the running system.
Key takeaways
- A successful cross-build still needs an architecture and ABI check.
- An epoll readiness notification still requires checking the result of the I/O call.
- Atomic file replacement and durability after power loss require different operations.
- MQTT acknowledgements describe protocol delivery and leave application effects to the application.
Reflect
- Explain to a colleague, in two sentences: configure a CMake cross-build and verify the target architecture.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageepoll(7): the epoll interface
- Man pageepoll_ctl(2): registering descriptors and EPOLLHUP
- Man pagerename(2): atomic replacement of a pathname
- Man pagefsync(2): synchronizing file and directory data
- Man pageunix(7): Unix-domain sockets
Official documentation first. Links checked when the lesson was published.