Full round 2 of 5 Medium JavaScript
Notification settings
A notification service with a settings cache: after one alert, users get SMS for everything. Then quiet hours, then a campaign that makes a thousand reads.
The real round is about an hour. Start the clock, do all four tasks out loud, and open an answer only when you’ve finished that task.
On this page
The handover
“This decides how we notify people. notify.js picks the channels for each message, settingsCache.js keeps users’ settings in memory, and store.js stands in for the settings table (it counts reads). Can you look at the SMS complaints first?”
The code
Read all 3 files before anything else. For each one, say in a sentence what it does, then follow one request through them.
notify.js
import { getSettings } from './settingsCache.js';
// Which channels to send this message on, for this user.
export async function channelsFor(userId, message) {
const settings = await getSettings(userId);
const channels = settings.channels;
if (message.urgent && !channels.includes('sms')) channels.push('sms');
return channels;
}
// The channels for every user in a campaign.
export async function sendCampaign(userIds, message) {
const plan = {};
for (const id of userIds) plan[id] = await channelsFor(id, message);
return plan;
}settingsCache.js
import { loadSettings } from './store.js';
const cache = new Map();
// A user's notification settings, cached for the life of the process.
export async function getSettings(userId) {
if (!cache.has(userId)) cache.set(userId, await loadSettings(userId));
return cache.get(userId);
}store.js
// A stand-in for the settings table. It counts reads, so you can see how many a request makes.
export const stats = { reads: 0 };
const TABLE = {
asha: { channels: ['push'], quiet: { from: 22, to: 7 } },
ravi: { channels: ['email', 'push'], quiet: null },
};
const DEFAULT = { channels: ['push'], quiet: null };
export async function loadSettings(userId) {
stats.reads++;
return structuredClone(TABLE[userId] ?? DEFAULT);
}
// Many users' settings in one round trip.
export async function loadMany(userIds) {
stats.reads++;
return Object.fromEntries(userIds.map((id) => [id, structuredClone(TABLE[id] ?? DEFAULT)]));
}Read every file first. After the report below, come back and click the line that causes it.
Line 6 doesn’t copy anything. So what does line 7 change?
1Fix the bug
Users who once received an urgent alert now get every notification by SMS too, even weekly digests, and SMS costs are climbing. Their saved settings in the database still say push only. Restarting the service makes it go away for a while.
Reproduce it
This example shows the report happening. Before reading on, work out why it prints what it does.
import { channelsFor } from './notify.js';
console.log((await channelsFor('asha', { text: 'Server down', urgent: true })).join(', '));
console.log((await channelsFor('asha', { text: 'Weekly digest' })).join(', '));It prints
push, sms push, sms
It should print
push, sms push
Your hypothesis
Say it out loud, or write it here, before you hunt for the line: which file, what’s going wrong, and what you’d check to prove it.
What a strong hypothesis says
A strong hypothesis says the settings are right in the database but wrong in memory (a restart fixes it), so something in this process changes them after they’re cached; and it names what: the urgent branch adds “sms” to a list that is shared with the cache.
Show the fix: the cause, the change and the test
The cause (notify.js, line 7)
notify.js line 7 pushes "sms" into channels, and channels is the very array stored in the cache: line 6 takes a reference, not a copy. After one urgent message the user’s cached settings include SMS, so every later message goes by SMS too, until a restart empties the cache. Return a new array instead of changing the cached one.
The fix
notify.js
4export async function channelsFor(userId, message) {5 const settings = await getSettings(userId);6 const channels = settings.channels;7 if (message.urgent && !channels.includes('sms')) channels.push('sms');7 if (message.urgent && !channels.includes('sms')) return [...channels, 'sms'];8 return channels;9}10 The test that proves it
It fails on the original code and passes once it’s fixed. Keep it, so the bug can’t come back.
import { channelsFor } from './notify.js';
await channelsFor('ravi', { text: 'Outage', urgent: true });
assert.deepEqual(await channelsFor('ravi', { text: 'hi' }), ['email', 'push']);2Check the AI
The assistant in the side panel is allowed. Before you found the cause, you asked it about the report. Would you act on its answer?
You
Why do users get SMS for normal messages after they once got an urgent alert?
Assistant
Your SMS provider is probably set to send every message by SMS once a phone number has been verified. Check the provider’s dashboard, or set channels: ['push'] explicitly in loadSettings so the default can’t include SMS.
Show what’s wrong with its answer
Neither is the cause. loadSettings returns a fresh copy with the right channels: call it directly and Asha’s are ['push']. And “a restart fixes it” rules out the provider: the wrong data lives in this process. Ask the assistant something you can check, like “can channelsFor change the cached settings object?”, and confirm where the data changes before touching config.
3Add a feature
Users can now set quiet hours, for example 22:00 to 07:00 (settings.quiet = { from: 22, to: 7 }). During quiet hours, non-urgent messages go on no channel; urgent ones still go. Callers will pass the user’s local hour: channelsFor(userId, message, hour). Without an hour, behave as before.
Start from your fixed code. Say the feature back as a contract, ask about its edges, then build it with a test.
Show one way to build it
The approach
Quiet hours can run past midnight (22 to 7), so the check has two cases. Urgent messages skip it. Keeping the old behaviour when no hour is passed means existing callers don’t change, and the campaign function passes the hour through.
The change
notify.js
1import { getSettings } from './settingsCache.js';2 3// Which channels to send this message on, for this user.4export async function channelsFor(userId, message) {3// True if hour (0 to 23) is inside quiet hours, which may run past midnight (22 to 7).4function isQuiet(quiet, hour) {5 if (!quiet) return false;6 return quiet.from <= quiet.to ? hour >= quiet.from && hour < quiet.to : hour >= quiet.from || hour < quiet.to;7}8 9// Which channels to send this message on, for this user. hour is the user's local hour, if known.10export async function channelsFor(userId, message, hour) {5 const settings = await getSettings(userId);12 if (!message.urgent && hour !== undefined && isQuiet(settings.quiet, hour)) return [];6 const channels = settings.channels;7 if (message.urgent && !channels.includes('sms')) return [...channels, 'sms'];8 return channels;9}10 11// The channels for every user in a campaign.12export async function sendCampaign(userIds, message) {19export async function sendCampaign(userIds, message, hour) {13 const plan = {};14 for (const id of userIds) plan[id] = await channelsFor(id, message);21 for (const id of userIds) plan[id] = await channelsFor(id, message, hour);15 return plan;16}The test
It fails before the feature and passes after; the bug’s test still passes too.
import { channelsFor } from './notify.js';
assert.deepEqual(await channelsFor('asha', { text: 'digest' }, 23), []);
assert.deepEqual(await channelsFor('asha', { text: 'digest' }, 6), []);
assert.deepEqual(await channelsFor('asha', { text: 'digest' }, 12), ['push']);
assert.deepEqual(await channelsFor('asha', { text: 'down', urgent: true }, 23), ['push', 'sms']);
assert.deepEqual(await channelsFor('ravi', { text: 'digest' }, 23), ['email', 'push']);4Make it faster
A campaign to 1,000 users on a cold cache makes 1,000 reads from the settings table, one round trip each, and the campaign takes minutes. The store has loadMany(ids). Make a campaign do one read for all the users it doesn’t have cached.
First count what it does too much of. Then change it without changing what it returns, and say what the change costs.
Show the speed-up and why it works
Why it’s slow, and the fix
One read per user is the N+1 problem in another shape. Loading every missing user with a single loadMany before the loop turns N round trips into one; the one-user path stays as it is for single messages.
The change
settingsCache.js
1import { loadSettings } from './store.js';1import { loadMany, loadSettings } from './store.js';2 3const cache = new Map();4 ⋯7 if (!cache.has(userId)) cache.set(userId, await loadSettings(userId));8 return cache.get(userId);9}10 11// Loads everyone in userIds who isn't cached yet, in one read.12export async function warm(userIds) {13 const missing = userIds.filter((id) => !cache.has(id));14 if (missing.length === 0) return;15 const loaded = await loadMany(missing);16 for (const id of missing) cache.set(id, loaded[id]);17}notify.js
1import { getSettings } from './settingsCache.js';1import { getSettings, warm } from './settingsCache.js';2 3// True if hour (0 to 23) is inside quiet hours, which may run past midnight (22 to 7).4function isQuiet(quiet, hour) {⋯15 return channels;16}17 18// The channels for every user in a campaign.18// The channels for every user in a campaign: their settings are loaded in one read first.19export async function sendCampaign(userIds, message, hour) {20 await warm(userIds);20 const plan = {};21 for (const id of userIds) plan[id] = await channelsFor(id, message, hour);22 return plan;The test
It fails on the code before the speed-up and passes after. Every earlier test still passes, so the behaviour didn’t change.
import { sendCampaign } from './notify.js';
import { stats } from './store.js';
const users = Array.from({ length: 50 }, (_, i) => 'user' + i);
const plan = await sendCampaign(users, { text: 'Sale' });
assert.equal(stats.reads, 1);
assert.deepEqual(plan.user7, ['push']);Sum it up
Score yourself
Tick what you really did. Interviewers score the process, so be honest: anything unticked is what to practise in the next round.
0 of 8