Full answer
Requirements to confirm first: how many links per day, how long they live, custom aliases, analytics, and the read to write ratio (often 100 to 1 or more).
API
- POST /links with { url, alias? } returns 201, { code, shortUrl }. Creating the same URL twice may return the same code (idempotent) or a new one.
- GET /:code answers with a redirect: 301 is cached by browsers (fast, but you lose click counts and cannot change the target), 302 or 307 is not cached (better for analytics and edits).
- 404 for unknown codes, 409 for an alias that exists, 400 for bad input.
Code generation
- Counter plus base62 (0-9, a-z, A-Z): 7 characters give about 3.5 trillion values. No collisions, but codes are guessable in order. Add an offset or shuffle bits if guessing matters.
- Random codes (for example 7 random base62 characters): not guessable, but need a unique-constraint check and a retry when a collision happens.
- A distributed counter: a database sequence, or each app instance takes a block of ids (for example 1000) from a central counter.
Safety
- Accept only http and https schemes, limit length, and block internal addresses (see the SSRF item) if you fetch titles.
- Rate limit creation per user or IP, and check abuse (phishing) with a block list.
Scaling reads
- Cache code to URL in Redis or in memory with a TTL, put a CDN in front for 301 responses, and keep the database as the source of truth with an index on the code.
- Count clicks asynchronously (queue or batch) so redirects stay fast.
javascript
const http = require('node:http');
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(n) {
let out = '';
do { out = ALPHABET[n % 62] + out; n = Math.floor(n / 62); } while (n > 0);
return out;
}
const byCode = new Map(); // code -> { url, clicks }
const byUrl = new Map(); // url -> code (same URL gives the same code)
let counter = 1_000_000; // start at one million so the first codes are not one character
function create(url, alias) {
let parsed;
try { parsed = new URL(url); } catch { return { status: 400, error: 'invalid url' }; }
if (!['http:', 'https:'].includes(parsed.protocol)) return { status: 400, error: 'only http and https are allowed' };
if (alias) {
if (!/^[A-Za-z0-9_-]{3,30}$/.test(alias)) return { status: 400, error: 'bad alias' };
if (byCode.has(alias)) return { status: 409, error: 'alias taken' };
byCode.set(alias, { url: parsed.href, clicks: 0 });
return { status: 201, code: alias };
}
if (byUrl.has(parsed.href)) return { status: 200, code: byUrl.get(parsed.href) };
const code = toBase62(counter++);
byCode.set(code, { url: parsed.href, clicks: 0 }); byUrl.set(parsed.href, code);
return { status: 201, code };
}
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/links') {
let body = '';
req.on('data', (c) => { body += c; if (body.length > 2048) req.destroy(); });
req.on('end', () => {
let input = {};
try { input = JSON.parse(body); } catch {}
const result = create(input.url, input.alias);
res.writeHead(result.status, { 'content-type': 'application/json' }).end(JSON.stringify(result));
});
return;
}
const entry = byCode.get(req.url.slice(1));
if (!entry) return res.writeHead(404).end();
entry.clicks++; // a real service would count asynchronously
res.writeHead(302, { Location: entry.url }).end();
});
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const post = async (body) => { const r = await fetch(base + '/links', { method: 'POST', body: JSON.stringify(body) }); return [r.status, await r.json()]; };
const [s1, a] = await post({ url: 'https://example.com/a/very/long/path?x=1' });
console.log('create ->', s1, JSON.stringify(a), '| code length:', a.code.length);
const [s2, b] = await post({ url: 'https://example.com/a/very/long/path?x=1' });
console.log('same URL again ->', s2, 'same code:', b.code === a.code);
console.log('alias ->', (await post({ url: 'https://example.org', alias: 'school' }))[0], '| alias again ->', (await post({ url: 'https://example.net', alias: 'school' }))[0]);
console.log('javascript: URL ->', (await post({ url: 'javascript:alert(1)' }))[0], '| not a URL ->', (await post({ url: 'hello' }))[0]);
const redirect = await fetch(base + '/' + a.code, { redirect: 'manual' });
console.log('redirect ->', redirect.status, redirect.headers.get('location'));
console.log('unknown code ->', (await fetch(base + '/nope', { redirect: 'manual' })).status, '| clicks counted:', byCode.get(a.code).clicks);
console.log('base62 of 3844 (62 squared):', toBase62(3844));
server.close();
});A small in-memory service handles creation, aliases, bad schemes and redirects. A real service replaces the Maps with a database and a cache. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): create -> 201 {"status":201,"code":"4c92"} | code length: 4 same URL again -> 200 same code: true alias -> 201 | alias again -> 409 javascript: URL -> 400 | not a URL -> 400 redirect -> 302 https://example.com/a/very/long/path?x=1 unknown code -> 404 | clicks counted: 1 base62 of 3844 (62 squared): 100
Key points
- Counter plus base62 gives short collision-free codes.
- 301 is cached by browsers, 302 keeps control and analytics.
- Validate the scheme and rate limit creation.
- Reads dominate, so cache them.
- Count clicks asynchronously.
Common mistakes
- Using 301 and then being unable to change or count a link.
- Accepting javascript: or file: URLs.
- Random codes with no unique constraint or retry.
- Hashing the URL and truncating it, which causes collisions.
- No rate limit on link creation.
Follow-ups
- How do you generate ids across several app instances?
- How would you expire links or let owners delete them?
- How would you store click analytics at high volume?
Tips
- Ask about read to write ratio first.
- Compare counter and random codes.
- Mention 301 versus 302.