Design a Desktop OS Notification Framework with AI Collaboration
System DesignModel answerLast updated
Architect a local operating system notification system for desktop apps and use an AI assistant to refine specific low-level logic safely.
Architect a desktop OS-level notification manager that allows native applications to publish, update, and manage alerts shown to the user. This system must handle local and remote inputs, enforce user preferences, and survive system restarts.
During this problem, you are expected to demonstrate how you would collaborate with an AI assistant to design or implement a critical subset of this system (such as the client API, local storage schema, or IPC dispatch logic).
Key Requirements & Constraints
-
Lifecycle & Control:
- Applications must be able to publish, modify, and revoke notifications.
- Notifications have priority levels, expiration times, and potential action buttons.
- The user must be able to mute specific apps, enable Do-Not-Disturb (DND) modes, and view historical alerts in a persistent action center.
-
System Architecture:
- High isolation: Untrusted client applications must not crash the central manager or block other applications.
- Persistence: Notification state must persist across system reboots until cleared or expired.
- Resource Constraints: Low memory footprint, responsive UI (sub-50ms latency from dispatch to render), and fair queuing to mitigate spammy applications.
-
AI Collaboration Exercise:
- Provide an initial prompt to generate a core component (e.g., the C++ IPC client library interface or the central manager's thread-safe queue dispatch mechanism).
- Detail your evaluation strategy for the generated output, identifying potential risks (hallucinated APIs, concurrency flaws, deadlocks, missing edge cases).
- Show how you refine the prompt to produce an enterprise-grade solution.
Expectation
Provide an architectural overview detailing component interaction, security boundaries, and data flow. Then, illustrate your interactive prompting workflow to construct and validate a specific component of the system.
Hints
Hint 1
Consider using Inter-Process Communication (IPC) via Unix Domain Sockets or Named Pipes to decouple untrusted client applications from the core notification daemon.
Hint 2
Ensure application limits are enforced via token-bucket rate limiting inside the central service to prevent a rogue app from exhausting disk space or UI resources.
Hint 3
When evaluating AI responses for low-level system design, explicitly check for thread safety, non-blocking I/O, resource cleanup (RAII), and robust error handling.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Architecture & System Design
1. High-Level Architecture
The system uses a client-daemon model to isolate desktop applications from the rendering thread and central notification database.
+------------------+ +------------------+
| App Process A | | App Process B |
+--------+---------+ +--------+---------+
| |
| (IPC / Named Pipes) | (IPC / Named Pipes)
v v
+-------------------------------------------------------+
| OS Notification Daemon |
| |
| +-------------------+ +----------------------+ |
| | IPC Receiver | --> | Rate Limiter / | |
| | (Auth & Validate) | | Priority Queue | |
| +-------------------+ +----------+-----------+ |
| | |
| +-------------------+ +----------v-----------+ |
| | Persistent Store | <-- | Policy Engine | |
| | (SQLite DB) | | (DND / User Rules) | |
| +-------------------+ +----------+-----------+ |
| | |
+---------------------------------------|---------------+
v
+-----------------------+
| Display Manager & |
| Action Center UI |
+-----------------------+
Core Components
- Client Library (
libnotification): Embedded in third-party applications. Exposes non-blocking asynchronous APIs to create, update, or revoke notifications. - Notification Daemon (
notificationd):- IPC Listener: Accepts connections over platform IPC (e.g., Windows Named Pipes / DBus / Unix Sockets). Validates application credentials (AppID, PID).
- Rate Limiter & Quota Manager: Uses a token-bucket algorithm per AppID to prevent application spamming.
- Policy Engine: Checks system state (Do Not Disturb, Focus Assist, fullscreen games) and per-application configuration (muted, badge-only, priority overrides).
- Storage Engine: Embedded transaction-safe database (SQLite) recording notification state, history, and actions.
- Display Engine / Action Center UI: Compositor-level UI process responsible for rendering transient toast popups and rendering the persistent notification drawer.
2. Notification Lifecycle & Data Flow
Creation & Rendering
- App calls
PublishNotification(payload). - Client library serializes payload and pushes it across non-blocking IPC to
notificationd. notificationdauthenticates caller identity via IPC socket credentials, assigns a system-wideNotificationID, and passes it through the Rate Limiter.- Policy Engine checks settings:
- If app is muted, write to DB marked as
silent_archived(no visual toast). - If DND is active and priority < High, append to SQLite history without raising visual popup.
- If allowed, trigger toast overlay UI via desktop compositor.
- If app is muted, write to DB marked as
- Notification stays on screen for a default timeout (e.g., 5 seconds) unless specified as persistent.
Update & Revocation
- Update: Calling
UpdateNotification(notification_id, new_payload)replaces content in SQLite and updates the active toast UI element in-place without playing audio again. - Revocation: Calling
CancelNotification(notification_id)removes active toasts and soft-deletes the record from SQLite (or flags it as dismissed).
3. Edge Cases & Isolation Guarantees
- Unresponsive/Crashing Apps: The client SDK runs asynchronously. If the client app crashes immediately after issuing an IPC request, the daemon safely processes or cleans up the request. If the user clicks an action on a crashed app's notification, the daemon attempts to relaunch the app using its registered background protocol handler.
- Daemon Restart: All pending active notifications reside in SQLite (
status = 'ACTIVE'). On daemon reboot, active toasts are restored directly to the Action Center drawer without re-triggering sound effects. - IPC Flooding: If an app emits > 20 requests/sec, the daemon drops excess messages and returns a
RATE_LIMIT_EXCEEDEDerror code over the socket.
Part 2 — Building Core Logic with an AI Assistant
1. Initial Prompt Strategy
We want to generate the thread-safe dispatch queue inside notificationd that receives raw IPC payloads, parses them, applies rate limiting, and forwards valid items to the storage engine.
Prompt 1 (Initial Context & Intent)
"Write a C++17 thread-safe NotificationDispatcher class for a desktop OS notification daemon. It should receive notification structs from multiple IPC threads, enqueue them, rate-limit callers using a token-bucket per AppId (max 10 notifications per second per app), and process them on a single worker thread that writes to a database. Include methods for publish, update, and cancel."
2. Output Evaluation & Vulnerability Analysis
Upon reviewing the initial AI output, a strong engineer checks for specific systems issues:
- Concurrency Bugs: Did the AI use
std::mutexandstd::condition_variablecorrectly? Are there potential deadlocks if callbacks invoke external methods while holding locks? - Blocking Operations: Does the IPC thread block if the queue is full? (It should drop or return an error immediately).
- Memory Ownership: Are payloads passed by value, std::shared_ptr, or unique_ptr? Are dangling references possible?
- Rate-Limiting Correctness: Does the token bucket purge stale application entries to prevent memory leaks over long daemon runtimes?
3. Refined Prompting
The initial output often uses naive std::map lookups under global mutexes without memory cleanup for inactive applications. We prompt with explicit constraints:
Prompt 2 (Refinement)
"Refine the
NotificationDispatcherclass with the following requirements:
- Use non-blocking enqueue: if the main queue exceeds 1000 total items, drop low-priority items and return
false.- Implement the token-bucket rate limiter with cleanup logic for inactive
AppIdkeys to prevent unbounded map growth.- Use
std::unique_ptr<NotificationRequest>for zero-copy ownership transfer into the worker thread.- Ensure no lock is held while executing the database write callback."
4. Final Solution Implementation
Below is the validated, robust implementation resulting from the AI refinement cycle:
#include <iostream>
#include <string>
#include <unordered_map>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <memory>
enum class ActionType { PUBLISH, UPDATE, CANCEL };
struct NotificationRequest {
std::string notification_id;
std::string app_id;
std::string title;
std::string body;
int priority; // 0 = Low, 1 = Normal, 2 = High
ActionType action;
std::chrono::steady_clock::time_point timestamp;
};
class TokenBucketRateLimiter {
private:
struct Bucket {
double tokens;
std::chrono::steady_clock::time_point last_updated;
};
std::unordered_map<std::string, Bucket> buckets_;
std::mutex mutex_;
const double max_tokens_ = 10.0;
const double fill_rate_per_sec_ = 10.0;
public:
bool Allow(const std::string& app_id) {
std::lock_guard<std::mutex> lock(mutex_);
auto now = std::chrono::steady_clock::now();
auto& bucket = buckets_[app_id];
if (bucket.last_updated.time_since_epoch().count() == 0) {
bucket.tokens = max_tokens_;
bucket.last_updated = now;
} else {
auto elapsed = std::chrono::duration<double>(now - bucket.last_updated).count();
bucket.tokens = std::min(max_tokens_, bucket.tokens + elapsed * fill_rate_per_sec_);
bucket.last_updated = now;
}
if (bucket.tokens >= 1.0) {
bucket.tokens -= 1.0;
return true;
}
return false;
}
void CleanupStaleEntries(std::chrono::seconds max_age) {
std::lock_guard<std::mutex> lock(mutex_);
auto now = std::chrono::steady_clock::now();
for (auto it = buckets_.begin(); it != buckets_.end(); ) {
if (now - it->second.last_updated > max_age) {
it = buckets_.erase(it);
} else {
++it;
}
}
}
};
class NotificationDispatcher {
private:
static constexpr size_t MAX_QUEUE_SIZE = 1000;
std::queue<std::unique_ptr<NotificationRequest>> queue_;
std::mutex queue_mutex_;
std::condition_variable cv_;
bool stopping_ = false;
TokenBucketRateLimiter rate_limiter_;
std::thread worker_thread_;
void WorkerLoop() {
while (true) {
std::unique_ptr<NotificationRequest> req;
{
std::unique_lock<std::mutex> lock(queue_mutex_);
cv_.wait(lock, [this]() { return !queue_.empty() || stopping_; });
if (stopping_ && queue_.empty()) {
break;
}
req = std::move(queue_.front());
queue_.pop();
}
// Lock released before executing database / dispatch operations
ProcessRequest(std::move(req));
}
}
void ProcessRequest(std::unique_ptr<NotificationRequest> req) {
// Simulating DB write and policy check without holding queue mutex
std::cout << "[Worker] Processing "
<< (req->action == ActionType::PUBLISH ? "PUBLISH" : "UPDATE")
<< " for App: " << req->app_id
<< " | ID: " << req->notification_id << std::endl;
}
public:
NotificationDispatcher() {
worker_thread_ = std::thread(&NotificationDispatcher::WorkerLoop, this);
}
~NotificationDispatcher() {
{
std::lock_guard<std::mutex> lock(queue_mutex_);
stopping_ = true;
}
cv_.notify_all();
if (worker_thread_.joinable()) {
worker_thread_.join();
}
}
bool Enqueue(std::unique_ptr<NotificationRequest> req) {
if (!rate_limiter_.Allow(req->app_id)) {
std::cerr << "[Dispatcher] Rate limit exceeded for App: " << req->app_id << std::endl;
return false;
}
{
std::lock_guard<std::mutex> lock(queue_mutex_);
if (queue_.size() >= MAX_QUEUE_SIZE) {
if (req->priority < 2) { // Drop low/normal priority when queue is saturated
std::cerr << "[Dispatcher] Queue full. Dropping request from: " << req->app_id << std::endl;
return false;
}
}
queue_.push(std::move(req));
}
cv_.notify_one();
return true;
}
};