Skip to content

Internationalization and Localization

Intermediate 54 min read Part 10 of 18

Build for every language and region: Unicode, locales, ICU plurals, time zones, currencies, RTL, translation pipelines, collation and locale-aware caching.

Summary#

Internationalisation (i18n) is engineering a system so that it can work in any language, script, region and culture without code changes. Localisation (l10n) is the work of adapting it for a specific locale: translating text, formatting dates and money, adjusting layouts and content. (The abbreviations count the letters between the first and last: i-18-n, l-10-n.) i18n is architecture and happens once. l10n is a continuous content pipeline that runs per locale, forever.

Getting it right touches every layer:

  • Text: Unicode everywhere, stored as UTF-8, with normalisation so that visually identical strings compare equal. Count graphemes, not bytes.
  • Locales: identified by BCP 47 tags (en-US, pt-BR, zh-Hant-TW) and chosen by negotiation: explicit choice, then account setting, then Accept-Language, then a fallback chain.
  • Messages: ICU MessageFormat with CLDR plural rules, because languages have up to six plural forms. Never concatenate strings.
  • Time: store instants in UTC. Store future local events as local time plus an IANA zone ID. Format with the user's calendar and conventions.
  • Numbers and currency: locale-specific separators and digits, ISO 4217 currency codes, integer minor units, and currency kept separate from locale.
  • Layout: right-to-left scripts need mirrored layouts (CSS logical properties) and bidi isolation.
  • Translation pipeline: string extraction, a TMS, translation memory, machine translation plus review, pseudo-localisation in CI, and over-the-air string bundles.
  • Data: locale-aware collation for sorting and uniqueness, and per-language tokenisation and stemming for search (CJK and Thai have no spaces).
  • Delivery: locale-aware caching, with the locale in the URL or a normalised cache key instead of raw Vary: Accept-Language.
  • Law: data residency for the regions you serve, which is separate from language.

Why It Exists#

Most users don't speak English. Native English speakers are a minority of internet users. Wikipedia has editions in over 300 languages, and large consumer products routinely ship in 50–100+ locales. A product that works only in English, US dates and dollars caps its market. In many countries, users strongly prefer, and regulators sometimes require, their own language for terms, prices and receipts.

Retrofitting i18n is very expensive. Typical problems found late:

  • hard-coded strings in thousands of files;
  • database columns that can't store emoji or Chinese;
  • concatenated sentences that can't be translated;
  • dates stored in server-local time;
  • money stored as floats;
  • layouts that break with 30% longer German text or right-to-left Arabic;
  • search that can't tokenise Japanese.

Each is cheap to avoid on day one and expensive to fix with years of data and code behind it. A single wrong choice, like MySQL's legacy 3-byte utf8 charset, has forced painful migrations of large production databases.

Bugs are subtle and user-visible. Examples:

  • "You have 1 messages".
  • A meeting that shifts by an hour after a daylight-saving change.
  • Prices shown as "1.000" that mean one thousand to Germans and one to Americans.
  • A name list sorted "correctly" for English, with "Åsa" among the A's, which looks wrong to a Swedish user, who expects Å after Z.
  • A username "аpple" (Cyrillic а) that impersonates "apple".

These erode trust, cause financial errors, and in the case of homographs, enable phishing.

It's a systems problem, not just a UI problem. Locale affects APIs (what format do dates travel in?), databases (encoding, collation, per-locale content tables), search (per-language analysers), caching (one URL, many language variants), notifications (render in the recipient's locale), payments (currencies and minor units), and compliance (residency, consent text per jurisdiction).

How It Works#

i18n vs l10n: who does what#

Internationalisation (i18n)Localisation (l10n)
WhatMake the system capable of any localeAdapt it to one locale
WhoEngineers, architectsTranslators, regional PMs, legal, marketing
WhenOnce, early; then maintainedContinuously, per release, per locale
ExamplesUnicode storage; message externalisation; locale negotiation; ICU formatting; RTL-capable layouts; locale-aware searchTranslating strings; local date and number conventions (from CLDR); local images, colours, payment methods; legal text; regional pricing
Failure looks likeCan't add a language without code changesWrong or missing translation, culturally off content

Two related terms are worth knowing. Globalisation (g11n) is the umbrella term covering both, plus business concerns (pricing, payment methods, regulation). Translation (t9n) is just the text part of l10n. Culturalisation goes beyond text: imagery, colours, examples, names, address formats and even feature sets. In some markets, cash on delivery or a local payment wallet is required for checkout to work at all.

Unicode, UTF-8 and normalisation#

Unicode assigns every character in every writing system a number, called a code point, written U+0041 for "A". The code space runs from U+0000 to U+10FFFF, which is 1,114,112 possible code points in 17 planes. Only about 150,000 are currently assigned, covering scripts, symbols and emoji. Plane 0, the Basic Multilingual Plane (BMP), holds most modern scripts. Emoji, rare CJK ideographs and historic scripts live in the supplementary planes.

An encoding turns code points into bytes:

  • UTF-8 (designed by Ken Thompson and Rob Pike in 1992, standardised in RFC 3629) uses 1 to 4 bytes. Code points below 128 (ASCII) take 1 byte and are byte-identical to ASCII. Most Latin, Greek, Cyrillic, Hebrew and Arabic characters take 2 bytes. Most CJK characters take 3 bytes. Emoji and supplementary characters take 4 bytes. UTF-8 is self-synchronising (you can find character boundaries from any byte) and has no byte-order issues, and it's the encoding of well over 95% of web pages. Use UTF-8 for storage, APIs, files and the wire.
  • UTF-16 uses 2 or 4 bytes, with surrogate pairs for code points above U+FFFF. It's the internal string type of JavaScript, Java, C# and Windows, which is why "😀".length === 2 in JavaScript.
  • UTF-32 uses a fixed 4 bytes. It's simple, but wasteful, and rarely used for storage.

Three levels of "character". Bugs come from confusing them:

  1. Bytes: what storage limits and network sizes count. "日本" is 6 bytes in UTF-8.
  2. Code points: what Unicode assigns. "é" can be one code point (U+00E9) or two (U+0065 "e" plus U+0301 combining acute accent).
  3. Grapheme clusters: what a user perceives as one character. The family emoji 👨‍👩‍👧 is five code points (three person emoji joined by two zero-width joiners), 18 bytes in UTF-8, and 8 UTF-16 code units, yet it's one grapheme. A Devanagari syllable or a flag emoji (two regional indicator symbols) is also one grapheme made of several code points.

Rules that follow from this:

  • Length limits for user-visible fields ("name up to 50 characters") should count graphemes (using Intl.Segmenter or ICU BreakIterator), while also enforcing a byte limit for storage.
  • Truncation must cut at grapheme boundaries. Cutting mid-sequence produces broken characters or half a family emoji.
  • Cursor movement, reversal and "first letter" logic must use grapheme segmentation.

Normalisation. Because "é" has two encodings (precomposed and decomposed), two strings can look identical but differ in bytes. Unicode Standard Annex #15 defines four normalisation forms:

  • NFC (canonical composition): combine into precomposed characters where possible. This is the common choice for storage and interchange, and what most keyboards and the web produce.
  • NFD (canonical decomposition): split into base plus combining marks. macOS's HFS+ file system stored filenames in a variant of NFD, which caused classic cross-platform filename mismatches.
  • NFKC and NFKD (compatibility forms) also fold "compatibility" variants: the ligature "fi" → "fi", fullwidth "A" → "A", superscript "²" → "2". They lose information, so use them for matching and identifiers (usernames, search keys), not for storing what the user typed.

The practice: normalise to NFC at system boundaries (API input) before storing, comparing or hashing. Use NFKC plus case folding for identifiers and search keys. Compare with case folding (Unicode's casefold), not toLowerCase, because lowercasing is locale-dependent:

  • In Turkish, "I" lowercases to dotless "ı", and "i" uppercases to dotted "İ".
  • In German, "ß" uppercases to "SS".

The infamous "Turkish I bug" breaks code that does toUpperCase() on identifiers under a Turkish locale.

Security: confusables and homographs. Different scripts contain look-alike characters: Latin "a" vs Cyrillic "а", Latin "o" vs Greek "ο". An attacker can register "pаypal" with a Cyrillic а. Defences follow Unicode Technical Standard #39 (security mechanisms):

  • Restrict identifiers to a single script, or allowed combinations (Latin plus Han plus Hiragana for Japanese, for example).
  • Check against a confusables skeleton so that look-alike variants of existing names are blocked.
  • Show Punycode (xn--...) in place of mixed-script domain names, as browsers do for suspicious IDNs.

Databases and encodings. Database encodings and collations deserve attention:

  • MySQL's utf8 was historically an alias for utf8mb3, at most 3 bytes per character. It can't store emoji or other supplementary characters, and silently truncates or errors on them. Always use utf8mb4, which is the default since MySQL 8.0, with a modern collation such as utf8mb4_0900_ai_ci.
  • PostgreSQL databases should use encoding UTF8. Collations come from the OS's libc or from ICU.
  • Index sizes: in MySQL, a VARCHAR(255) in utf8mb4 can need up to 1,020 bytes, which matters for index prefix limits.
  • Every hop must agree: client libraries, connection charsets, files, message queues and logs all need to be UTF-8 end to end. "Mojibake" (garbled text like "é" for "é") comes from a UTF-8 byte sequence being decoded as Latin-1 somewhere along the path.

Locales and language negotiation#

A locale is a bundle of user preferences: language, region, script and sometimes calendar, numbering system and collation. It's identified by a BCP 47 language tag (IETF Best Current Practice 47, built on RFC 5646):

  • en is English; en-US is English as used in the United States; en-GB is British English.
  • pt-BR vs pt-PT: Brazilian and European Portuguese differ in vocabulary and spelling.
  • zh-Hans-CN vs zh-Hant-TW: the script subtag (Simplified vs Traditional Han) matters more than the region. Use zh-Hans/zh-Hant to choose translations, and region for formatting.
  • sr-Latn vs sr-Cyrl: Serbian is written in both Latin and Cyrillic.
  • Unicode extensions (-u-) carry preferences: de-DE-u-co-phonebk (German phonebook collation), th-TH-u-nu-thai (Thai digits), ar-SA-u-ca-islamic (Islamic calendar), en-US-u-hc-h23 (24-hour clock).

Keep three things separate, because conflating them causes most locale bugs:

ConceptExampleDrives
Language (UI locale)GermanWhich translation strings you show
Region / formatting localeSwitzerlandNumber, date, currency and address formats
Jurisdiction / marketSwiss customer, data stored in EUPrices, tax, legal text, data residency, features

A German speaker living in Spain may want a German UI, euro prices with Spanish VAT, and dates formatted the German way. An IP address in France doesn't mean the user reads French: think tourists, VPNs and multilingual countries like Belgium, Switzerland, India and Canada.

Negotiation: deciding which locale to serve. A typical precedence order, from strongest to weakest signal:

  1. Explicit user choice: a saved account preference, or a selection made in the UI.
  2. Locale in the URL: /fr/..., fr.example.com or ?hl=fr. This is explicit, shareable and cacheable, and search engines can index each version.
  3. A cookie from a previous choice (for anonymous users).
  4. The Accept-Language header from the browser or OS, e.g. Accept-Language: fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7. RFC 9110 defines the q-values (quality weights, 0 to 1).
  5. Geo-IP hints: weak. Use them to suggest a region ("Looks like you're in Japan, switch?"), not to force-redirect.
  6. The default locale.

Matching and fallback. You rarely support exactly what the user asks for, so a matcher finds the best supported locale. Then a fallback chain fills gaps in partially translated content:

  • Request pt-BR; you support pt-PT and en. Either serve pt-PT (understandable, but spelling differs) or en. CLDR's language-matching data scores distances such as "pt-BR to pt-PT is close" and "en-AU to en-GB is closer than to en-US".
  • A string missing in fr-CA falls back to fr, then to the source language (en). Never show a raw key like checkout.button.pay.
  • Fallback must also apply to formatting data. If you support the language sw (Swahili) but your formatting library lacks sw-KE data, fall back to sw, not to en-US dates.

Propagation. Once chosen, the locale has to flow everywhere downstream:

  • Through API calls: an Accept-Language or X-Locale header passed along service-to-service, or a field in the request context.
  • Into async jobs: emails, push notifications and PDFs are rendered later, often by a different service. Store the recipient's preferred locale and time zone on the user record, and render at send time in the recipient's locale, not the sender's or the server's.
  • Into logs and errors: keep error codes language-neutral (PAYMENT_DECLINED) and translate them at the edge. A machine-readable code plus a localised message lets clients and support teams work in any language.

CLDR and ICU: don't hand-roll locale data. The Unicode Common Locale Data Repository (CLDR) is the shared database of locale conventions: date patterns, number symbols, plural rules, currency names, time zone display names, collation rules, units and language-matching data. Apple, Google, Microsoft and IBM all build on it. ICU (International Components for Unicode) is the reference library that implements Unicode algorithms using CLDR data, in C/C++ (ICU4C) and Java (ICU4J). Browsers and Node.js expose much of it through the ECMAScript Intl API (Intl.DateTimeFormat, NumberFormat, PluralRules, Collator, Segmenter, RelativeTimeFormat, ListFormat, DisplayNames). Writing your own "date format per country" table is a classic mistake. It'll be incomplete and wrong, and it won't get CLDR's twice-yearly updates.

Message formats, plurals and ICU MessageFormat#

Externalise every user-facing string into message catalogues keyed by an ID. Never concatenate translated fragments:

  • Bad: "You have " + n + " new " + (n == 1 ? "message" : "messages"). Word order differs by language (Japanese puts the verb last, German moves verbs to the end of subordinate clauses). Plural rules differ. Grammatical gender and case change surrounding words.
  • Good: one complete message with placeholders, so translators can reorder and inflect.

Plural rules vary a lot. CLDR defines six plural categories: zero, one, two, few, many and other. Each language uses a subset, chosen by rules over the number:

LanguageCategories usedExample rule
Japanese, Chinese, Korean, Thaiother onlyNo grammatical plural
English, Germanone, other1 is one; everything else, including 0 and 1.5, is other
Frenchone, many, other0 and 1 are both one ("0 message")
Russian, Polish, Ukrainianone, few, many, otherPolish: 1 one; 2–4, 22–24 few; 5–21 many
Arabiczero, one, two, few, many, otherAll six
Welshzero, one, two, few, many, otherSix, with irregular rules

There are also ordinal rules ("1st, 2nd, 3rd, 4th" in English; "1er, 2e" in French), selected with Intl.PluralRules(locale, type: ordinal).

ICU MessageFormat is the de facto standard syntax for this. A message can contain:

  • Arguments: a named placeholder for a value.
  • plural: branches by CLDR plural category, with # standing for the formatted number, plus exact-value branches such as =0.
  • select: branches on a keyword, typically grammatical gender ("He/She/They replied").
  • selectordinal: ordinal branches.
  • Formatted arguments: number, date and time formatting with styles, so "3.5 GB" and dates are localised inside the sentence.
inbox.summary =
  {count, plural,
    =0    {You have no new messages}
    one   {You have # new message}
    other {You have # new messages}}
 
comment.reply =
  {gender, select,
    female {{name} replied to her post}
    male   {{name} replied to his post}
    other  {{name} replied to their post}}

A Polish translator writes one, few, many and other branches for the same key. The code is unchanged, and the runtime chooses the branch with that locale's rules.

Other message-format systems:

  • gettext (ngettext with Plural-Forms headers in .po files): the classic in C, Python, PHP and Linux.
  • Mozilla Fluent: asymmetric localisation, where the translator can add variants the source language doesn't need.
  • MessageFormat 2.0: Unicode's successor to ICU MessageFormat, designed by the Unicode MessageFormat Working Group and published as part of the CLDR/LDML specification. Library support (ICU, JavaScript polyfills and a proposed Intl.MessageFormat) is still rolling out, so check maturity before you adopt it.
  • Android plurals resources and iOS .stringsdict (now String Catalogs), which also follow CLDR categories.

Message-authoring rules engineers should enforce:

  • One message per sentence. No fragments, and no building sentences from parts.
  • Named placeholders ({userName}), not positional %s. Translators need to know what each one is and to reorder them.
  • Put context and descriptions on every key ("Button label on checkout page, max 20 characters"). The English "Save" can be "save a file" or "save money", which are different words in most languages.
  • Don't reuse a key across contexts just because the English text matches.
  • Don't embed markup in ways translators can break. Use rich-text tags in the message (<b>…</b> as named tags) rather than splitting strings around HTML.
  • Lists ("Alice, Bob and Carol") use Intl.ListFormat, because conjunctions and commas differ ("Alice, Bob y Carol"; Chinese uses "、").
  • Names: don't assume first name/last name order or that every name has both parts. Many East Asian conventions put the family name first, Indonesian mononyms exist, and Spanish names often carry two surnames. Prefer a single "full name" field plus an optional "what should we call you" field.

Dates, time zones and calendars#

Store instants in UTC; display in the user's zone. For events that have happened (an order placed, a message sent), store a UTC timestamp (timestamptz in PostgreSQL, Unix epoch milliseconds or an RFC 3339 string with Z) and convert at display time with the viewer's IANA zone. Keep the time-and-ordering pitfalls (clock skew, ordering) separate from presentation.

Future events are different. "Team standup every Monday 09:00 in Berlin" or "Concert 20:00 local time on 14 March 2028" should be stored as local date-time plus IANA time zone ID (Europe/Berlin), not pre-converted to UTC. Governments change time zone rules, sometimes with only weeks' notice: daylight saving time is abolished or adopted, or an offset is moved. A UTC timestamp computed today could be an hour wrong by then. Compute the UTC instant when needed, using the current tz database. For recurring events, expand occurrences from the rule (RFC 5545 iCalendar RRULE) in the event's zone, so that 09:00 stays 09:00 across DST changes.

The IANA time zone database (tzdata, also called the Olson database) maps zone IDs like America/New_York, Asia/Kolkata and Asia/Kathmandu to their full history of offsets and DST rules. It's updated several times a year. Your servers, language runtimes, databases and mobile apps each embed a copy, and they must be updated. A stale tzdata in an app means wrong times for users in an affected country. Things to remember:

  • Never store bare offsets as zones. +01:00 doesn't tell you whether summer will be +02:00. Store the offset with an instant (RFC 3339 2026-03-29T09:00:00+02:00) for an audit-accurate local time. Store the zone ID for future and recurring scheduling.
  • Offsets aren't all whole hours: India is +05:30, Nepal +05:45 and New Zealand's Chatham Islands +12:45/+13:45. Offsets range from -12:00 to +14:00 (Kiribati's Line Islands).
  • Days aren't always 24 hours. A DST day is 23 or 25 hours. Some local times don't exist (the 02:00–03:00 gap on spring-forward) or occur twice (fall-back). Your scheduler needs a policy for each: shift forward, or pick the earlier or later occurrence. In 2011 Samoa moved across the International Date Line and skipped 30 December entirely.
  • "Today" depends on the zone. Daily quotas, streaks, "orders today" reports and calendar-day billing must say whose midnight they mean: the user's, the merchant's or UTC.
  • Date-only values (birthdays, holidays, hotel check-in dates) are not instants. Store them as DATE, not as midnight UTC, or a birthday shifts by a day when viewed in another zone.

Calendars and conventions. Gregorian isn't universal:

  • The Islamic (Hijri) calendar (several variants, including islamic-umalqura used in Saudi Arabia).
  • The Hebrew calendar.
  • The Persian (Solar Hijri) calendar, official in Iran and Afghanistan.
  • The Thai Buddhist calendar, where the year is the Gregorian year + 543 (2026 is 2569).
  • The Japanese imperial era calendar. Reiwa began 1 May 2019, and systems had to ship a new era name with short notice; well-built ones only needed a CLDR/ICU data update.
  • Week start (Sunday in the US, Monday in most of Europe, Saturday in parts of the Middle East), weekend days (Friday–Saturday in several Gulf states) and week numbering (ISO 8601 weeks vs US weeks) all vary.
  • Date order (MM/DD vs DD/MM vs YYYY-MM-DD) and 12- vs 24-hour clocks follow the locale.

Format with skeletons (Intl.DateTimeFormat(locale, { dateStyle: 'medium' }), or ICU's yMMMd) and let CLDR pick the pattern. Never hard-code MM/dd/yyyy. For interchange, always use ISO 8601 / RFC 3339, which is unambiguous, sortable and locale-free. JavaScript's legacy Date is error-prone (mutable, local-time-centric). The Temporal proposal introduces Temporal.Instant, ZonedDateTime and PlainDate types that model exactly these distinctions. Java's java.time (JSR 310), Python's zoneinfo and Rust's chrono-tz do similar jobs.

Numbers and currencies#

Number formatting differs by locale in decimal separator, grouping separator, grouping size and digits:

Locale1234567.89 formats asNotes
en-US1,234,567.89Comma groups, dot decimal
de-DE1.234.567,89The reverse of English
fr-FR1 234 567,89Narrow no-break space (U+202F) groups
de-CH1’234’567.89Apostrophe-like group separator
en-IN / hi-IN12,34,567.89Indian lakh/crore grouping: first 3, then 2s
ar-EG١٬٢٣٤٬٥٦٧٫٨٩Arabic-Indic digits by default in some locales

Consequences for engineers:

  • Never parse user-entered numbers with a locale-blind parser. "1.234" is one thousand two hundred thirty-four in Germany and one point two three four in the US. Parse with the user's locale, or use input controls that produce a canonical value.
  • Keep the canonical form locale-free. Use JSON numbers, or decimal strings with a dot, in APIs and storage. Format only at the presentation edge.
  • The French separator is a no-break space. Tests comparing against a normal space fail, and string matching on formatted numbers is fragile.
  • Native digits: Arabic, Persian, Hindi (Devanagari), Bengali, Thai and others have their own digits. Accept them on input (normalise to ASCII digits before validation, or a phone-number field rejects "٠١٢٣") and choose deliberately on output, with the -u-nu- extension.
  • Compact and unit formatting ("1.2K", "1,2 Mio.", "12万") and units (km vs miles, °C vs °F, kg vs lb, A4 vs Letter paper) come from CLDR too. Use Intl.NumberFormat with notation: 'compact' or style: 'unit'. Which unit system to use is a regional preference: the US uses miles, the UK uses miles on road signs but metric elsewhere. A ride-hailing app shows kilometres in Hyderabad and miles in Chicago, driven by the region, not the UI language.

Currencies have their own rules, set by ISO 4217:

  • Codes: USD, EUR, JPY, INR, KWD. Always store the currency code next to the amount. Never infer the currency from the locale: an en-US user can pay in EUR.
  • Minor units: USD and EUR have 2 decimals (cents). JPY and KRW have 0 (¥1,000, not ¥1,000.00). KWD, BHD, OMR and JOD have 3 (fils, baisa). This determines how you store amounts and how payment processors expect them.
  • Store money as integer minor units (amount_minor BIGINT + currency CHAR(3)), or as an exact DECIMAL(19,4). Never as binary floating point: 0.1 + 0.2 !== 0.3. See the payment system case study for ledger implications.
  • Formatting depends on the display locale, not the currency: €1,234.56 in en-IE, 1.234,56 € in de-DE, 1 234,56 € in fr-FR. Symbol position, spacing and symbol choice ("$" vs "US$" vs "USD") vary. The bare "$" is ambiguous across USD, CAD, AUD and MXN, so show "US$" or "CA$" when users might be confused.
  • Rounding rules: cash rounding (CHF to 0.05; some countries round cash to 0.05 or 0.10 after dropping their smallest coins), banker's rounding (round half to even) in some financial contexts, and per-line vs per-total tax rounding.
  • Exchange rates must be stored with a timestamp and source, and the converted amount must be frozen at transaction time. Re-converting later with today's rate rewrites history. Show converted prices as estimates, and charge in a currency the processor settles.
  • Localised pricing is a business decision, not a conversion. Psychological price points (€9.99, not €10.37), purchasing-power pricing and tax-inclusive display (Europe shows VAT-inclusive prices; the US usually adds sales tax at checkout) all differ.

Right-to-left (RTL) and bidirectional text#

Arabic, Hebrew, Persian (Farsi) and Urdu are written right to left, together used by hundreds of millions of people. But real RTL text is bidirectional: numbers, Latin brand names, URLs and code embedded in it still run left to right. The Unicode Bidirectional Algorithm (UBA, Unicode Standard Annex #9) gives each character a directional type (strong L, strong R/AL, weak numbers, neutral punctuation). It then resolves embedding levels to compute the visual order from the stored logical order. Text is always stored in logical (reading) order. Rendering reorders it for display.

What breaks, and the fixes:

  • Layout mirroring. The whole UI flips for RTL: the navigation drawer is on the right, back arrows point right, progress bars fill right to left. Set <html dir="rtl" lang="ar"> and use CSS logical properties (margin-inline-start, padding-inline-end, inset-inline-start, text-align: start) instead of left and right. Flexbox and grid then follow the writing direction automatically. Android (start/end attributes) and iOS (leading/trailing constraints) have equivalent mechanisms.
  • Not everything mirrors. Mirror directional icons (back, forward, "reply", a list's indent), but not logos, media playback controls (play still points right by convention), clocks, checkmarks or charts with a numeric x-axis. Phone numbers and credit card numbers stay LTR.
  • Mixed-direction strings. A Hebrew sentence containing an English product name and a trailing "!" can render with punctuation on the wrong side. User-generated content of unknown direction should be wrapped in an isolate: HTML <bdi>, dir="auto", or Unicode isolate controls (FSI U+2068 … PDI U+2069) when inserting values into messages. That stops a username like "مریم" from reordering the surrounding text. ICU and many i18n libraries can wrap placeholders in isolates automatically.
  • Input fields should use dir="auto", so a user typing Arabic in a search box sees correct direction, and LTR emails stay LTR.
  • Security. Bidi control characters can disguise filenames ("invoice‮fdp.exe" displayed as "invoiceexe.pdf"). The Trojan Source attack (Boucher and Anderson, 2021, CVE-2021-42574) hid malicious logic in source code reviews using bidi overrides. Strip or escape bidi overrides (U+202A–U+202E, U+2066–U+2069) in identifiers, filenames and code.
  • Fonts and shaping. Arabic letters change shape by position (initial, medial, final, isolated) and need a shaping engine (HarfBuzz is the common one). Indic scripts need complex shaping too. Server-side rendering of images and PDFs with text needs proper fonts and shaping, or it produces disconnected letters.

Translation pipelines and string storage#

There are two very different kinds of translatable text, with different pipelines:

  1. UI strings, owned by your team: buttons, labels, emails, error messages. Thousands to tens of thousands of keys, changed with each release.
  2. Content: product descriptions, articles, help-centre pages, CMS content. Potentially millions of items, often edited by non-engineers. This may include user-generated content (UGC) such as reviews, posts and messages, which you may want to machine-translate on demand.

UI string pipeline (continuous localisation):

  1. Developers add keys in the source language with descriptions and max-length hints, in a resource format:
    • JSON/YAML with ICU messages (web);
    • gettext .po/.pot;
    • XLIFF (the XML Localisation Interchange File Format, an OASIS standard for exchanging with translation tools);
    • Android strings.xml;
    • iOS .strings/.stringsdict or String Catalogs (.xcstrings);
    • Java .properties.
  2. CI extracts and validates them: no duplicate keys, valid ICU syntax, placeholders present. Then it pushes new strings to a Translation Management System (TMS): Crowdin, Lokalise, Phrase, Smartling, Transifex, or Mozilla's open-source Pontoon.
  3. The TMS pre-fills from translation memory (TM: previously translated segments, matched exactly or fuzzily) and a glossary/termbase (approved terms: "cart" is always "Warenkorb"). It may also run machine translation (neural MT such as Google Translate, DeepL or Amazon Translate, or LLM-based) for human post-editing.
  4. Translators work with context: screenshots, the description, character limits and an in-context editor that shows the string in the real UI. Lack of context is the biggest cause of bad translations.
  5. Linguistic QA and automated checks: placeholder parity, ICU syntax per locale (all required plural categories present), length overflow, forbidden terms.
  6. Translations sync back as a PR, or are published directly as versioned bundles to a CDN or object store.
  7. Runtime loading: the app loads only the bundle for the resolved locale (code-splitting per locale and per route), with a fallback chain for missing keys. Mobile apps can fetch over-the-air (OTA) bundle updates to fix a translation without an app-store release, keeping bundled translations as the offline fallback.

Release models. A string freeze stops changes N days before release so translators can catch up. It's simple, but slows shipping. Continuous localisation lets strings flow to the TMS on every merge, so features ship with whatever locales are ready. Feature flags hide features in locales whose translations aren't complete, or fall back to the source language with a "translation in progress" policy.

Pseudo-localisation is a must-have test. Transform source strings into an accented, expanded and bracketed form: "Save" becomes "[Šåvé ẋẋ]". Running the UI in this pseudo-locale exposes:

  • hard-coded strings (they stay plain English);
  • truncation and layout breaks, because translations are often 30–40% longer than English (German and Finnish especially, and short strings can double);
  • concatenation bugs;
  • encoding problems.

An RTL pseudo-locale (with forced mirroring) catches layout direction bugs before Arabic translations exist.

Storing translatable content in your database. For content that exists in many languages, there are common schemas:

  • Translation table (most common): a base table holds language-neutral data (product_id, price_minor, sku). A product_translation(product_id, locale, name, description, updated_at, source_hash) table has a primary key of (product_id, locale). Query with the fallback chain: try pt-BR, then pt, then the default. This is easy to index per language, and a translation can be added without schema changes.
  • Generic translation table: translation(entity_type, entity_id, field, locale, value). It's flexible, but has no type safety and gets heavy with joins. Use it only for small, varied fields.
  • JSON/JSONB column: name JSONB such as "en": "Shoe", "de": "Schuh" (as a JSON object). Simple to read and good for a handful of locales. But it's harder to search or index per language, and rows grow with every locale.
  • Column per locale (name_en, name_de): avoid. Every new language becomes a migration.

Track staleness. When the source text changes, mark translations stale (compare source_hash) and re-queue them for translation, rather than silently showing outdated text. For UGC, store the original with a detected language, and translate on demand ("See translation") with caching keyed by (content_id, target_locale, model_version). Users should always be able to see the original.

Machine translation and LLMs. Neural MT and LLMs have changed the economics. First drafts are nearly free, and quality is high for common language pairs. Production practice:

  • Use MT plus human post-editing for UI and marketing text.
  • Use raw MT (clearly labelled) for UGC and long-tail content.
  • Use glossaries and "do not translate" lists for brand names.
  • Add automated quality estimation to route low-confidence segments to humans.
  • Remember that legal and safety text needs human review.
  • MT costs per character add up at scale, so cache and deduplicate.

Collation, search and tokenisation per language#

Collation is locale-aware sorting and comparison. Sorting by code point (what ORDER BY does with a binary collation, or Array.sort() with no comparator) gives nonsense for users: all uppercase before lowercase, and accented letters after "z". Correct order depends on language:

  • In Swedish and Finnish, "ä", "ö" and "å" are separate letters sorted after "z". In German, "ä" sorts with "a" (dictionary order) or as "ae" (phonebook order).
  • In Spanish, traditional collation treated "ch" and "ll" as single letters. Modern collation doesn't, but "ñ" is still a separate letter after "n".
  • In Lithuanian, "y" sorts between "i" and "j".
  • In Chinese, sorting can be by pinyin (romanised pronunciation), stroke count or radical. Japanese names sort by their kana reading, which you often need to store separately (the "furigana" field on Japanese forms exists for this).

The Unicode Collation Algorithm (UCA, Unicode Technical Standard #10) defines a multi-level comparison using the Default Unicode Collation Element Table (DUCET). CLDR adds per-language tailorings on top. Strength levels control what counts as different:

LevelDistinguishesExample "equal" at this level and below
PrimaryBase letters"a" = "á" = "A"
SecondaryAccents"a" ≠ "á", but "a" = "A"
TertiaryCase and variants"a" ≠ "A"
Quaternary / identicalPunctuation, code point tie-breaksRarely needed

An "accent-insensitive, case-insensitive" collation (MySQL's _ai_ci) compares at primary strength.

Collation is a database design decision, not only a display one:

  • Indexes are ordered by collation. An index built with one collation can't serve ORDER BY in another. Sorting by the user's locale in SQL needs an expression index (CREATE INDEX ... (name COLLATE "sv-SE-x-icu")) or sorting in the application.
  • Uniqueness depends on collation. With a case- and accent-insensitive collation, "José" and "jose" collide in a UNIQUE username index. That may be what you want for usernames, but it surprises people for other fields.
  • Collation versions change. PostgreSQL using glibc collations was hit when glibc 2.28 (2018) changed sort order for many locales. Indexes built under the old version silently became corrupt in order, so lookups and uniqueness checks could miss rows after an OS upgrade until REINDEX. PostgreSQL now records collation versions and warns on mismatch. Many teams prefer ICU collations (CREATE COLLATION ... (provider = icu, locale = 'de-DE')), which version explicitly. PostgreSQL 17 added a built-in C.UTF-8 provider for stable code-point order.
  • Sort keys. ICU can produce a binary sort key for a string and locale. Storing it in a column gives fast, index-friendly locale ordering for a fixed locale, but the key changes when the ICU version changes.

Full-text search across languages. Search engines like Elasticsearch, OpenSearch and Solr (all built on Lucene) build an inverted index from tokens. Producing good tokens is language-specific:

  • Word segmentation. Chinese, Japanese and Thai don't use spaces between words. A whitespace tokenizer indexes a whole sentence as one token, which makes search useless. Options:

    • dictionary-based segmenters: Kuromoji or Sudachi for Japanese, SmartCN, jieba or IK for Chinese, and the ICU tokenizer (dictionary-based for Thai, Lao, Khmer, Myanmar, CJK);
    • n-grams: CJK bigrams, which are robust and language-agnostic, but make a bigger index and are noisier.

    Korean uses spaces, but words agglutinate, so it needs a morphological analyser (Nori in Elasticsearch).

  • Normalisation and folding. Lowercase with locale awareness, remove or keep accents (ICU folding maps "é" to "e" for matching), apply NFKC (fullwidth "ABC" becomes "ABC", and half-width katakana is normalised), and convert between Traditional and Simplified Chinese when appropriate.

  • Stemming and lemmatisation. Reduce "running/runs/ran" to a root. Snowball stemmers exist for many European languages; Arabic needs light stemming and normalisation of letter variants (alef forms, taa marbuta); Hebrew needs prefix handling. Over-stemming hurts precision.

  • Decompounding. German, Dutch and the Nordic languages build compounds ("Donaudampfschifffahrt"). A search for "Schiff" should find the compound, which needs a decompounder with a dictionary.

  • Stop words, synonyms and transliteration. Stop words and synonyms are per language. Transliteration lets "Moskva" match "Москва", and users type Hindi in Latin script ("Hinglish") or Japanese romaji.

Architectures for multilingual indexes:

  1. A field per language (title.en, title.de, title.ja), each with its own analyser. The query searches the fields for the user's languages. This is good when content is translated, and documents carry multiple languages.
  2. An index per language. Simplest for analysers and relevance tuning. Route documents by detected language and queries by UI or query language. More indexes means more operational overhead.
  3. One field with a generic analyser (ICU tokenizer plus folding) plus n-grams. This is the fallback for UGC in unknown or mixed languages. Precision is lower.

Language identification decides which analyser to use for UGC: libraries such as Google's CLD3, fastText's lid.176 model (176 languages) or the ICU-based detectors in search engines. Short texts ("ok", "lol", product names) are often misdetected, so combine the detector with the author's locale and keep a mixed fallback field.

Autocomplete is especially language-sensitive. Japanese users type kana that an input method editor (IME) converts to kanji, so suggestions must be indexed by reading as well. Chinese users type pinyin. Edge n-grams don't work well for languages without spaces. See the search autocomplete case study for the trie and ranking side.

Character counting and limits. Twitter's 2017 move to 280 characters used weighted counting: CJK characters count as 2. A 280-character limit would have meant far more content in Japanese, where tweets were already rarely hitting 140 because each character carries more information. Length limits are product decisions that differ by script.

Locale-aware caching and CDNs#

Locale multiplies your cache key space, and done naively it destroys hit ratios. (See CDNs and scaling reads for the general caching picture.)

The Vary: Accept-Language trap. If an origin returns HTML chosen by Accept-Language and sets Vary: Accept-Language, the CDN caches a separate copy for every distinct header value. Browsers send thousands of variants (en-US,en;q=0.9, en-US,en;q=0.9,fr;q=0.8, en-GB,en-US;q=0.9,en;q=0.8…), so you get near-zero hit ratios and origin overload. Some CDNs respond by refusing to cache such responses at all, which is no better. Fixes:

  1. Put the locale in the URL (/de/products/42). The cache key is naturally the URL, each locale caches separately and well, users can share links, and search engines can index each version. This is the recommended default for public content.
  2. Normalise at the edge. If you must negotiate, have the CDN or edge function parse Accept-Language, match it against your supported locales and write the result into a custom header or cache key (X-Locale: de). The cache varies on that small set (say 30 values), not on raw headers. See edge computing.
  3. Serve locale-neutral HTML and fetch strings separately. A single cached shell plus a per-locale message bundle. This is good for SPAs, but adds a request (and a flash of untranslated text, unless the bundle is preloaded).

SEO and redirects. Mark alternates with hreflang link tags (<link rel="alternate" hreflang="de" href=".../de/...">, plus x-default) so search engines serve the right version per user. Avoid forced geo-IP or Accept-Language redirects on every visit. They trap travellers and VPN users, and they can keep crawlers (which often crawl from one country, without Accept-Language) from seeing other locales. Suggest instead with a banner, and remember the user's choice in a cookie.

Translation bundle caching. Publish bundles as content-hashed, immutable files (/i18n/de.3f9a1c.json) with Cache-Control: public, max-age=31536000, immutable. A small, short-TTL manifest (or the HTML) points to the current hash. A translation fix becomes a new hash and new manifest, and the change is visible immediately without purging the CDN. The same versioned-key idea applies to server-side caches. Include the bundle version or translation updated_at in keys like page:42:de:v17, so a translation update naturally misses the old entry instead of needing a fleet-wide invalidation.

Server-side caches. Every cache that stores rendered or formatted output needs the locale (and often the currency and time zone) in its key: rendered emails, search results with localised snippets, price strings, and API responses with formatted dates. A cleaner design caches locale-neutral data (amount_minor, currency, UTC timestamps, translation keys) and formats at the edge or client. One cache entry then serves all locales, and formatting is cheap.

Data residency: locale is not jurisdiction#

A user's language says nothing about which laws govern their data. A German speaker in the US is not an EU data subject because of their language, and a US company serving EU residents in English is still subject to GDPR. Residency, privacy and retention rules attach to the user's residence or the customer contract, not the UI locale:

  • Data residency laws and contracts: the EU's GDPR (restrictions on cross-border transfers), China's PIPL and data security rules, Russia's data localisation law, India's DPDP Act, and sector rules (health, finance). Enterprise customers often demand "EU data stays in the EU" regardless of law.
  • The architecture is usually regional deployments or cells: an EU stack with its own databases and backups, and a US stack. Each user or tenant is pinned to a home region (see multi-tenancy and multi-region data). Global services (login, routing) hold only minimal, non-personal routing data. Remember logs, analytics, search indexes, caches and support tools: residency leaks most often happen through these side channels.
  • Retention and erasure rules differ by jurisdiction too. The data lifecycle page covers deletion across replicas and backups.
  • Local requirements beyond data: content rules, age gating, tax invoicing formats (e-invoicing mandates), payment methods, accessibility law, and required languages (Quebec's Charter of the French Language requires French; Canada's federal services are bilingual).

Model three separate fields on the user or tenant: ui_locale, formatting_locale/time_zone/currency, and data_region/jurisdiction. Never derive one from another.

Notifications, emails and asynchronous rendering#

Asynchronous messages are where locale bugs hide, because the request that triggers them often isn't from the person who receives them. When Alice (en-US, New York) comments on Kenji's post (ja-JP, Tokyo), the notification must say "Aliceさんがコメントしました" in Japanese, with a timestamp in Tokyo time. The notification system should:

  • Store per-recipient preferences (locale, time zone, preferred units) on the user profile and read them at render time. Never use the triggering request's locale.
  • Store templates per locale with versioning, and render with the fallback chain. Emails need localised subject lines, sender names, footers and legal unsubscribe text.
  • Respect quiet hours in the recipient's zone (don't push at 03:00 local), and schedule digests at a local-time slot such as 08:00 in each user's zone. This turns a single nightly batch into a rolling 24-hour wave across zones, which also smooths load.
  • Limit lengths by script. SMS is limited to 160 GSM-7 characters, but a single non-GSM character (any Arabic, Hindi, Chinese or emoji) forces UCS-2 encoding with only 70 characters per segment. Multi-part messages cost more per segment. Pre-compute segment counts per locale.

When to Use It#

Internationalise early, before the first non-default locale, when any of these signals appear:

  • Your market roadmap includes more than one country or language, even a year out. The engineering work (Unicode correctness, externalised strings, locale-aware formatting, logical CSS) is cheap when done from the start and expensive to retrofit. Externalising strings from 2,000 screens later can cost engineer-months.
  • You store or display human text from users: names, addresses, posts, product titles. Even an English-only UI receives Unicode input (emoji, accented names, CJK usernames), so Unicode correctness is never optional.
  • You handle money, dates or scheduling across regions: marketplaces, travel (hotel booking, flight booking), payments, calendars, ride-hailing.
  • You run search or sorting over names or content in more than one language.
  • You're B2B SaaS selling to multinational customers, who'll ask for languages, residency and local compliance in procurement questionnaires.

Pick something else instead when:

  • Full localisation (many translated locales) is unjustified for a product with a single-country market and no plans to expand. Do the i18n foundations anyway (Unicode, UTC, no hard-coded formats, strings in catalogues) and defer translation.
  • Machine translation on demand beats curated translation for long-tail UGC, where human translation of every post is unaffordable.
  • A locale-neutral API design (codes, ISO formats, minor units) is better than server-side formatting when clients are diverse. Let each client format with its platform's Intl/ICU.

When NOT to Use It#

  • Don't build your own locale data, plural rules, time zone math or collation. Use CLDR/ICU, platform Intl, IANA tzdata and the database's ICU collations. Hand-rolled tables are always incomplete.
  • Don't translate internal tooling, logs or developer error messages unless your engineering org is multilingual. Keep logs in one language and use stable error codes.
  • Don't localise before the product works. Adding 20 languages to an early product multiplies the cost of every UI change by 20. Two or three priority locales plus pseudo-localisation in CI keeps the system honest until demand is proven.
  • Don't geo-redirect or auto-switch language based on IP alone. Suggest it, and let the user choose.
  • Don't translate legally binding text with raw MT. Terms, privacy policies, medical and safety instructions need professional translation and review.

How to Implement It#

  1. Make Unicode the default everywhere. UTF-8 for files, HTTP (Content-Type: text/html; charset=utf-8), databases (utf8mb4, PostgreSQL UTF8) and message queues. Normalise input to NFC at API boundaries. Count graphemes for user-visible limits and bytes for storage limits.
  2. Define the locale model. Pick supported locales (BCP 47 tags), the default, the fallback chains, and separate fields for UI language, formatting locale, time zone, currency and data region on the user or tenant.
  3. Negotiate once at the edge, then propagate. URL path for public pages; profile, then cookie, then Accept-Language for apps. Resolve to a supported locale, then pass the locale in request context to all services and async jobs.
  4. Externalise every string into catalogues with ICU MessageFormat, descriptions and length limits. Ban concatenation with a lint rule. Add a pseudo-locale (and an RTL pseudo-locale) to CI and to visual tests.
  5. Format at the edge, store neutral. UTC instants, local time plus zone for future events, DATE for calendar dates, integer minor units plus ISO 4217 code for money, numbers as numbers. Format with Intl/ICU using the formatting locale.
  6. Build layouts with logical properties and dir attributes. Isolate user-supplied text in messages. Mirror directional icons only.
  7. Set up the translation pipeline. Extraction in CI → TMS with translation memory, glossary and MT → human review with screenshots → automated checks → versioned, content-hashed bundles on the CDN → runtime loading with fallback.
  8. Design content tables for translation. A per-entity translation table keyed by (entity_id, locale), staleness tracking, original language preserved for UGC.
  9. Configure search per language. Language detection, per-language analysers or fields, ICU folding, CJK segmentation, and locale collations for sorted lists (via ICU collations or application-side sort keys).
  10. Make caching locale-aware without exploding it. Locale in URL or normalised cache key, immutable hashed bundles, versioned keys for translation changes, and caching of locale-neutral data where possible.
  11. Keep tzdata, CLDR and ICU updated across servers, runtimes, databases and mobile apps as a routine dependency.
// Locale-aware rendering with ICU MessageFormat + Intl (formatjs-style API)
import { IntlMessageFormat } from "intl-messageformat";
 
const SUPPORTED = ["en", "en-GB", "de", "fr", "pt-BR", "pt", "ja", "ar", "pl"];
 
function resolveLocale(requested: readonly string[]): string {
  for (const tag of requested) {
    const loc = new Intl.Locale(tag);
    // exact match, then language-only fallback (pt-BR -> pt)
    for (const cand of [loc.baseName, loc.language]) {
      if (SUPPORTED.includes(cand)) return cand;
    }
  }
  return "en";
}
 
const MSG = `{count, plural, =0 {No new orders} one {# new order} other {# new orders}} since {since, date, medium}`;
 
export function renderSummary(accept: string[], tz: string, count: number,
                              sinceUtcMs: number, amountMinor: bigint, currency: string) {
  const locale = resolveLocale(accept);
  const text = new IntlMessageFormat(MSG, locale, {
    date: { medium: { dateStyle: "medium", timeZone: tz } },
  }).format({ count, since: new Date(sinceUtcMs) });
  // ISO 4217 minor units: JPY 0, USD 2, KWD 3
  const digits = new Intl.NumberFormat("en", { style: "currency", currency })
    .resolvedOptions().maximumFractionDigits ?? 2;
  const price = new Intl.NumberFormat(locale, { style: "currency", currency })
    .format(Number(amountMinor) / 10 ** digits);
  const dir = ["ar", "he", "fa", "ur"].includes(new Intl.Locale(locale).language) ? "rtl" : "ltr";
  return { locale, dir, text, price };
}

(In production, the translated MSG comes from the locale's bundle, and you'd use a real CLDR-based matcher such as @formatjs/intl-localematcher rather than this simple loop. Convert minor units with a decimal library for very large amounts, since Number loses precision above 2^53.)

TechnologyFits when
ICU4C / ICU4JServer-side formatting, collation, segmentation and transliteration in C++, Java or JVM languages; the reference implementation
ECMAScript Intl (browsers, Node.js)Formatting dates, numbers, plurals, lists and relative time, plus collation and segmentation in JS without shipping locale data
FormatJS / react-intl, i18next, vue-i18n, LinguiWeb frameworks needing ICU messages, locale loading and React or Vue bindings
gettext (.po)C, Python (Django), PHP (WordPress) and Linux ecosystems with mature tooling
Mozilla FluentAsymmetric, grammar-heavy messages where translators need more flexibility than ICU
Android resources, iOS String CatalogsNative mobile apps; platform-standard plural and RTL support
Crowdin, Lokalise, Phrase, Smartling, TransifexHosted TMS with translation memory, MT, in-context editing and CI integration
Pontoon, WeblateOpen-source TMS for community and self-hosted localisation
DeepL, Google Cloud Translation, Amazon Translate, LLM APIsMachine translation for drafts, UGC and long-tail content
IANA tzdata + java.time, zoneinfo, TemporalCorrect time zone math; keep the data updated
PostgreSQL ICU collations, MySQL utf8mb4_0900 collationsLocale-aware ordering and comparison inside the database
Elasticsearch / OpenSearch analysis plugins (ICU, Kuromoji, Nori, SmartCN)Multilingual full-text search
CDN with edge functions (Cloudflare Workers, CloudFront Functions, Fastly Compute)Normalising locale into the cache key and handling locale routing at the edge

Trade-offs#

OptionProsConsPick when
Locale in URL path (/de/...)Cacheable, shareable, SEO-friendly, explicitURL management; switching locale changes the URLPublic, indexable content (the default)
Negotiate via Accept-LanguageZero-click, "just works"Cache key explosion unless normalised; bad for SEO; surprises travellersLogged-out app shells, with edge normalisation
Server-side formattingConsistent output; works for emails, PDFs, SMSLocale in every cache key; server needs locale dataAsync channels, SSR pages
Client-side formatting (neutral API)One cached response for all locales; uses platform dataClients must agree; old devices may lack locale dataAPIs consumed by many clients
Human translationHighest quality; brand voice; legal safetySlow, roughly per-word cost, needs contextUI, marketing, legal
MT + post-editFast, cheap first draftsQuality varies by language pair; needs reviewLarge volumes of UI and docs
Raw MT on demandCovers unlimited content and languagesErrors and tone; must be labelled; per-character costUGC, long-tail content
Translation table per entityIndexable per language; flexible localesJoins; fallback logic in queriesCatalogues, CMS content
JSONB translationsSimple; one rowHarder per-language indexing; row growthA few locales, small fields
String freezePredictable, complete releasesSlows shippingMobile releases, regulated products
Continuous localisationShip fast; translations follow quicklyPartially translated features need flags or fallbackWeb products with frequent deploys

Common Pitfalls#

  • Concatenating strings or reusing a fragment ("Delete" + " " + itemName), which makes correct grammar impossible in most languages.
  • Hard-coding plural logic as n == 1 ? singular : plural, which is wrong for Arabic, Polish, Russian, French zero and more.
  • Storing future events as UTC and showing them an hour off after a DST rule change. Or storing birthdays as timestamps, so they shift a day across zones.
  • Using utf8 (utf8mb3) in MySQL and losing emoji, or truncating multibyte strings mid-character in application code.
  • Using float for money or assuming 2 decimal places (JPY 0, KWD 3).
  • Deriving currency, region or jurisdiction from the UI language, or language from IP.
  • Vary: Accept-Language on CDN-cached pages, which collapses the hit ratio.
  • Using left/right in CSS and images with baked-in text, both of which break RTL and translation.
  • No context for translators, which produces wrong-sense translations ("Book" as a noun instead of the verb "reserve").
  • Measuring length in UTF-16 code units or bytes for user-visible limits, then truncating mid-emoji or mid-grapheme.
  • Uppercasing or lowercasing identifiers with the default locale (the Turkish I problem). Use locale-independent case folding for keys.
  • Forgetting async channels: emails, push, SMS and PDFs rendered in the server's or sender's locale.
  • Stale tzdata or ICU in containers and mobile apps after a government changes a time zone.
  • Changing OS or library versions under a database with libc collations without reindexing.

Real-World Examples#

  • Wikipedia / MediaWiki. Wikipedia exists in over 300 language editions. MediaWiki's interface messages are translated by volunteers on translatewiki.net into hundreds of languages, and it handles RTL wikis (Arabic, Hebrew, Persian, Urdu) from the same codebase. It's the canonical example of i18n infrastructure built once and localised by a community at massive scale.
  • Facebook / Meta. Facebook famously crowdsourced its translations in 2008 with a Translations app, where users proposed and voted on translations of UI strings. That brought dozens of languages online quickly. Its later work on large-scale machine translation (the "No Language Left Behind" research, 2022, covering 200 languages) targets low-resource languages for content translation.
  • Unicode CLDR and ICU. The CLDR project, run by the Unicode Consortium with contributions from Apple, Google, Microsoft, IBM, Meta and others, is the shared source of locale data. ICU is embedded in Android, Chrome, Node.js, many databases and most operating systems. So when you call Intl.NumberFormat, you're most likely using ICU with CLDR data.
  • Mozilla. Firefox ships in about 100 locales, using Fluent (Mozilla's message format) and Pontoon (its open-source localisation platform) for volunteer translators.
  • Twitter/X. In 2017 Twitter doubled the tweet limit from 140 to 280 for most languages, but kept Japanese, Chinese and Korean at the effective old limit through weighted character counting, where CJK characters count double. Its reasoning was that CJK tweets rarely hit the limit because those scripts are information-dense. This is a concrete case of length limits being per script.
  • PostgreSQL + glibc 2.28. When glibc 2.28 (2018) updated collation data, PostgreSQL indexes on text columns that relied on libc collations could become silently inconsistent after an OS upgrade. Linux distributions (Debian 10, RHEL 8) and the PostgreSQL community published warnings advising REINDEX. This led to collation versioning in PostgreSQL and wider use of ICU collations.
  • Japan's Reiwa era (2019). The new era name was announced on 1 April 2019, a month before it took effect. Systems that formatted Japanese calendar dates needed updated ICU/CLDR and OS data, and well-architected systems only had to update data, not code.
  • Time zone changes. Governments regularly change DST rules: Samoa's 2011 date-line jump, Egypt's on-again, off-again DST, and Mexico abolishing most DST in 2022. The IANA tz database ships releases several times a year. Calendar products, airlines and schedulers depend on getting these updates out quickly.
  • Uber-style regional products. Ride-hailing and delivery apps run per-city configuration: currency, units (km vs miles), tax rules, local payment methods (cash in some markets), language and regulatory features. They often use regional deployments for latency and data residency. The language and formatting layer is driven by the rider's locale, while pricing and regulation come from the city. See the ride-hailing case study.

Case studies that use this pattern#

In the Interview#

A sample walkthrough: "Design a global e-commerce catalogue in 25 languages."

  1. Requirements. Locales, plus whether to translate product content or only the UI. Prices in local currency? Residency constraints? SEO needs?
  2. Data model. product (neutral fields) plus product_translation(product_id, locale, title, description, source_hash), with a fallback chain. Prices in price(product_id, market, currency, amount_minor) as market-specific prices, not FX conversions.
  3. Pipeline. CMS edits in the source language → MT draft → human review for top products → publish. Mark translations stale on source change.
  4. Serving. /de-de/p/42 URLs with hreflang alternates. The CDN caches per path. Edge normalisation suggests a locale for bare URLs, without forcing a redirect.
  5. Search. Per-language fields with language analysers (German decompounding, Japanese Kuromoji) and a fallback ICU field.
  6. Scale numbers. 1M products × 25 locales × ~2 KB of text ≈ 50 GB of translations, which fits a sharded relational store plus a search cluster. Cache hit ratio stays high because the URL carries the locale. MT cost: at an illustrative ~$20 per million characters, 1M products × 1,000 characters × 24 target locales ≈ 24 billion characters ≈ $480k, so translate the popular head first and the long tail on demand.

Common follow-ups:

  • "How do you handle a user in Brazil who prefers English?" The explicit preference wins for the UI language. Formatting can stay pt-BR or follow the preference. Currency is set by the market (BRL), and residency by account region.
  • "A meeting is scheduled for 10:00 New York time next November and the US changes DST rules. What happens?" Because it's stored as local time plus America/New_York, it stays at 10:00 local after a tzdata update. Attendees in other zones see their converted time change, which is correct.
  • "Why not use Vary: Accept-Language?" The raw header has thousands of variants, so the cache fragments. Put the locale in the URL, or normalise to a supported set at the edge.
  • "How do you search Japanese text?" Morphological segmentation (Kuromoji or Sudachi) or bigrams, NFKC normalisation, and a reading (kana) field for autocomplete.
  • "How would you add Arabic to an existing app?" Audit CSS for physical properties, switch to logical properties plus dir, mirror directional icons, isolate embedded LTR values, test with an RTL pseudo-locale, and check fonts and shaping for server-rendered images and PDFs.
  • "How do you prevent homograph usernames?" NFKC plus case folding, single-script restriction per UTS #39, and a confusable-skeleton uniqueness check.
Deep Dive: Unicode internals, normalisation algorithms and text securityShow

UTF-8 bit layout. The encoding is a prefix code:

  • 1 byte: 0xxxxxxx (7 bits, U+0000–U+007F)
  • 2 bytes: 110xxxxx 10xxxxxx (11 bits, up to U+07FF)
  • 3 bytes: 1110xxxx 10xxxxxx 10xxxxxx (16 bits, up to U+FFFF)
  • 4 bytes: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx (21 bits, capped at U+10FFFF by RFC 3629)

Its useful properties follow from this layout:

  • ASCII compatibility: no multibyte sequence contains a byte below 0x80, so /, NUL and newline are never part of a multibyte character, and old byte-oriented code mostly works.
  • Self-synchronisation: continuation bytes always start with 10, so you can find the next boundary from any position.
  • Sortability: byte-wise order equals code point order.

Overlong encodings (encoding "/" as C0 AF) are invalid. Decoders that accepted them enabled path-traversal attacks, notably in early IIS (around 2000), so strict decoding is a security requirement. Treat invalid sequences as errors, or replace them with U+FFFD, never silently. Surrogate code points (U+D800–U+DFFF) are invalid in UTF-8. Lone surrogates from broken UTF-16 (common in JavaScript strings sliced mid-pair) become "WTF-8" if you're careless, so validate at boundaries.

Size math matters for capacity. A 280-character post is 280 bytes in English, about 560 in Russian or Arabic, and about 840 in Chinese or Japanese (3 bytes per character in UTF-8, where UTF-16 needs only 2). So for CJK-heavy corpora, UTF-16 storage is about a third smaller than UTF-8. Compression (zstd or LZ4 at the storage layer) mostly erases the difference, which is why UTF-8 everywhere remains the right default. Budget indexes and column limits in bytes: MySQL InnoDB's maximum index key prefix of 3,072 bytes means a utf8mb4 VARCHAR(768) is the largest fully indexable column.

How normalisation works. Every code point has a canonical combining class (0 for base characters, non-zero for combining marks, ordered by position: below, above and so on). NFD:

  1. recursively applies canonical decompositions (é → e + U+0301; Hangul syllables decompose algorithmically into jamo);
  2. applies canonical ordering, a stable sort of each run of combining marks by combining class.

This makes "a + dot below + acute" and "a + acute + dot below" identical. NFC then recomposes pairs that have a primary composite, except for a short composition exclusion list, which exists so that NFC output stays stable across Unicode versions. Unicode guarantees normalisation stability: a string normalised under one version stays normalised under later versions (for assigned characters), which is what makes normalised data safe to store as keys.

Performance. Most text is already NFC. Implementations use a quick check (NFC_QC property: Yes, No or Maybe) to skip work, so normalising ASCII or already-composed text is close to a memcpy. Normalise once at ingestion, not on every comparison.

Compatibility forms are lossy on purpose. NFKC maps "①" → "1", "カ" (half-width) → "カ", "ff" → "ff" and "ℌ" → "H". That's ideal for search and identifier matching, and wrong for storing user text: you'd change a mathematician's "ℌ" or a Japanese company's preferred half-width brand. The usual stack for identifier comparison (usernames, email local parts on your own service, tags) is:

  1. NFKC;
  2. case folding (full case folding maps ß → ss, and Greek final sigma ς → σ);
  3. NFKC again, because folding can de-normalise.

Unicode packages this as the derived property NFKC_Casefold. The IETF's PRECIS framework (RFC 8264, with profiles in RFC 8265 for usernames and passwords) standardises this for protocols.

Grapheme segmentation (UAX #29) uses rules over the Grapheme_Cluster_Break property:

  • don't break between CR and LF;
  • don't break before Extend or ZWJ characters;
  • don't break within emoji ZWJ sequences;
  • pair regional indicators for flags;
  • keep Hangul jamo sequences together;
  • (since Unicode 15.1) keep Indic conjuncts together.

The rules change with new Unicode versions, so segmentation results depend on your ICU version. That's another reason to update ICU, and a reason not to persist "grapheme counts" as truth.

Security layers, from cheapest to strongest:

  1. Strict decoding: reject invalid UTF-8, overlongs and lone surrogates.
  2. Normalisation of identifiers (NFKC_Casefold) before uniqueness checks. Otherwise "paypal" (fullwidth) and "paypal" are different users.
  3. Restriction levels (UTS #39): allow single-script identifiers, or "highly restrictive" mixes (Latin + Han + Hiragana + Katakana; Latin + Han + Bopomofo; Latin + Han + Hangul). Reject Latin+Cyrillic mixtures.
  4. Confusable detection: compute the skeleton (map each character to its prototype via the confusables table, e.g. Cyrillic "а" → Latin "a"). Reject a new identifier whose skeleton equals an existing one. Store the skeleton in an indexed column with a unique constraint.
  5. Invisible and control character stripping: zero-width joiners and non-joiners outside the contexts where they're required, bidi overrides, and tag characters. Trojan Source (Boucher and Anderson, 2021) showed that compilers accepted bidi overrides in comments and strings, so code could look different in review from what it executed. Many editors and code hosts now warn on such characters.
  6. IDN display policy: browsers show Punycode (xn--pple-43d.com for a Cyrillic "аpple") when the domain mixes scripts or doesn't match the user's languages. The Chromium IDN policy is a good reference.
Deep Dive: time zone and calendar correctness at scaleShow

What a tz database entry contains. Each zone (e.g. America/Sao_Paulo) is a list of eras, and each era has a standard offset, a rule set for DST and an abbreviation. The rules encode transitions such as "first Sunday of November at 00:00". Compiled into TZif binary files, a zone is just a sorted array of transition instants with the offset after each one. Converting an instant to local time is then a binary search over transitions (O of log n, and n is tiny), followed by adding the offset. Converting local time to an instant is harder, because the mapping isn't a function:

  • Gap (spring forward, e.g. 02:30 on the US DST start date doesn't exist): candidates are zero. A policy chooses between shifting forward by the gap length (java.time's default), throwing, or using the pre-transition offset.
  • Overlap (fall back, e.g. 01:30 happens twice): two candidates. Choose earlier (java.time's default), later, or require the user to disambiguate. Python's zoneinfo exposes this as the PEP 495 fold attribute. Temporal exposes disambiguation: compatible | earlier | later | reject.

Scheduling engines must re-resolve after tzdata updates. Suppose a system stores the meeting "2027-11-08 10:00 America/New_York", and also caches the computed UTC instant for indexing ("which reminders fire in the next minute?"). When a tzdata release changes the US rules, every cached instant for future events in affected zones becomes wrong. The robust design:

  1. Store local time plus zone as the source of truth.
  2. Store the derived UTC instant plus the tzdata version used to compute it.
  3. On deploying a new tzdata version, run a job that recomputes derived instants for future events in zones whose rules changed. The tz release notes list affected zones, and you can diff TZif files to find them.
  4. Make reminder and notification queues idempotent with respect to recomputation, so they can be rebuilt from the source of truth.

That's the same "derived data can be recomputed from the source of truth" principle as in time-and-ordering and event-driven systems.

Worked example: daily streak across zones. A user in Pacific/Auckland (UTC+13 in summer) completes a lesson at 23:30 local on Monday, which is Monday 10:30 UTC. Then they fly to America/Los_Angeles (UTC−8) and do a lesson at 20:00 local Monday, which is Tuesday 04:00 UTC. Did they keep the streak?

  • In UTC days, both lessons are distinct days, so the streak continues.
  • In "home zone" days (Auckland), the second lesson is Tuesday 17:00, so the streak continues.
  • In "current device zone" days, both are "Monday", so it's one day, and Tuesday's lesson is still needed.

There's no universally right answer. Pick a policy (most apps use the device's current zone, with grace periods for travel), document it, and record the zone with each event so the computation is reproducible.

Recurrence (RFC 5545 RRULE) pitfalls:

  • FREQ=MONTHLY;BYMONTHDAY=31 skips months without day 31. BYMONTHDAY=-1 means the last day.
  • "Every weekday at 09:00 Europe/London" must be expanded in the zone, not in UTC.
  • Exceptions (EXDATE) and overrides (RECURRENCE-ID) must match on the original local time.
  • Expanding unbounded rules needs a horizon: materialise the next N occurrences lazily, and re-expand after edits or tzdata changes.

Calendars beyond Gregorian. CLDR and ICU support Buddhist, Chinese, Coptic, Ethiopic, Hebrew, Indian (Saka), Islamic (civil, tabular and Umm al-Qura variants), Japanese, Persian and ROC calendars:

  • Islamic months traditionally begin with the sighting of the new crescent moon, so the actual date can differ by a day from computed calendars and by country. Systems often use the tabular or Umm al-Qura computed variants and allow an administrative adjustment.
  • The Hebrew calendar has leap months (a 13th month in 7 of every 19 years).
  • The Chinese calendar is lunisolar, with leap months determined astronomically.
  • The Japanese calendar adds an era every time a new emperor accedes. The Reiwa transition showed how a data-driven formatter avoids code changes. Note that Japanese date input forms often still need a Gregorian fallback, and the first year of an era is written 元年 ("gannen") rather than "1".

Store dates in Gregorian or ISO form internally. Treat other calendars as presentation, unless the business logic itself is calendar-specific (e.g. Ramadan schedules, Lunar New Year sales).

Leap seconds are a separate concern from time zones. UTC has had 27 positive leap seconds since 1972, and the General Conference on Weights and Measures resolved in 2022 to stop inserting them by 2035. Most systems smear them (Google's 24-hour linear smear) rather than repeating a second. That's covered on the time-and-ordering page. For i18n, the point is to never compute wall-clock durations by subtracting formatted strings.

Testing. Use a fixed clock injected into code. Test across at least:

  • a half-hour and a 45-minute zone (Asia/Kolkata, Asia/Kathmandu);
  • southern-hemisphere DST (Australia/Sydney, America/Sao_Paulo history);
  • a zone with a date-line change (Pacific/Apia around 2011);
  • the DST gap and overlap instants;
  • 29 February;
  • year boundaries with ISO week numbering (31 December can be in week 1 of the next year).

Property-based tests that round-trip instant → local → instant (outside gaps and overlaps) catch many bugs.

Deep Dive: multilingual search, collation sort keys and locale-aware caching at scaleShow

How UCA sort keys work. Each character maps to one or more collation elements, each a tuple of weights (primary, secondary, tertiary). For a string, the sort key concatenates all primary weights, then a separator, then all secondary weights, then tertiary. Comparing two strings becomes a memcmp of their sort keys. That's why a primary difference anywhere dominates any accent difference: "role" < "rôle" < "roles", because primary weights compare "role" vs "roles" before accents are considered. Some contractions (Slovak "ch" as one letter after "h") and expansions (German phonebook "ä" → "ae") are handled by tailoring the mapping.

ICU sort keys are compact (often 1–2× the UTF-8 length). That makes them practical to:

  • store in an indexed BYTEA column per locale, for locale-sorted paging (keyset pagination on (sort_key, id));
  • use as range keys in a key-value store, so sorted scans by name work per locale.

The catch is that keys are tied to the ICU/UCA version and the locale. Store collation_version next to them and rebuild on upgrade, the same lesson as the glibc incident.

Collation and distributed systems. If two services compare strings with different collations, joins and deduplication disagree. Typical cases are a database sorting with de-DE and a cache layer comparing bytes, or a primary and replica on different OS versions with libc collations. Pick one canonical comparison for identity (normalised bytes or NFKC_Casefold), and use locale collation only for presentation order. Keep keys used in uniqueness constraints and partitioning (shard keys) on byte or normalised comparisons, because a collation change must never move which shard a key belongs to.

Search relevance across languages. BM25 statistics (document frequency, average field length) are per field. Mixing languages in one field distorts IDF: a common German word looks rare in a mostly English corpus. That's one reason per-language fields or indexes rank better. Practical tuning:

  • Query-language detection is unreliable for 1–3 word queries. Search the user's UI language field and the fallback field, boost the UI-language match, and use the multi-match most_fields or best_fields strategy.
  • Cross-lingual retrieval: multilingual dense embeddings (e.g. LaBSE, multilingual E5 models) map queries and documents from different languages into one vector space, so a Spanish query can find English documents. Combine them with BM25 in a hybrid ranker. See the vector databases page for ANN indexing.
  • Index size: CJK bigram indexing roughly doubles the token count relative to segmented indexing. Per-language fields multiply storage by the number of populated languages per document, not by the number of supported languages, as long as documents only populate their own language fields.
  • Reindexing for analyser changes (a new dictionary for jieba or Kuromoji) needs a full reindex behind an alias swap, as with any Elasticsearch mapping change.

Locale-aware caching: worked numbers. A content site serves 50 locales, 200k pages and 2 billion page views a month. CDN behaviour under three designs:

DesignDistinct cache objectsEffect
Vary: Accept-Language, raw header200k pages × thousands of header stringsLong tail of variants; hit ratio can drop below 50% and origin load multiplies
Normalised locale key (50 values)200k × 50 = 10MPopular pages stay hot per locale; hit ratio similar to a single-locale site for the head
Neutral shell + per-locale bundle200k shells + 50 bundles per releaseHighest hit ratio; extra bundle fetch, cached as immutable

The second and third designs cap the key space at supported locales. The third also makes translation fixes cheap: one new bundle hash, and zero page purges.

Invalidation on translation updates. With versioned keys, a translation publish increments i18n_version for the locale (or, at finer grain, per namespace such as checkout). Pages embed the version, or the server includes it in keys (render:page42:de:v18). Old entries simply age out. This avoids a thundering herd of purges and gives instant visibility, the same "change the key, don't purge the value" technique as content-hashed static assets.

Edge negotiation cost. Parsing Accept-Language and matching against 50 locales is microseconds in an edge function, far cheaper than an origin round-trip. Keep the supported-locale list and match table in the function bundle, or in an edge KV store if it changes often.

Data residency and caching. CDN caches are global by default. If pages contain personal data subject to residency rules, either don't cache them at shared edges (Cache-Control: private), or use CDN features that restrict caching or processing to specific regions (several CDNs offer EU-only processing options). Locale-specific public pages carry no personal data and can be cached globally.

Key Takeaways#

  • i18n is engineering done once; l10n is content work done per locale. Do the i18n foundations from day one, even for a single-language product.
  • Use UTF-8 everywhere (utf8mb4 in MySQL). Normalise to NFC at boundaries. Count graphemes for user-visible limits and bytes for storage. Use NFKC_Casefold plus confusable checks for identifiers.
  • A locale is a BCP 47 tag. Negotiate it once (URL, then profile, then cookie, then Accept-Language), match with fallback chains, and propagate it to every service and async job. Keep UI language, formatting, currency and jurisdiction as separate fields.
  • Never concatenate strings. Use ICU MessageFormat with CLDR plural categories (1 to 6 per language), select for gender, and give translators context.
  • Store instants as UTC, future events as local time plus IANA zone, and calendar dates as DATE. Keep tzdata updated and re-resolve after rule changes.
  • Store money as integer minor units plus an ISO 4217 code (JPY 0, USD 2, KWD 3 decimals). Format by display locale, freeze FX at transaction time, and never use floats.
  • RTL needs logical CSS properties, dir, selective icon mirroring and bidi isolation for embedded values. Strip bidi overrides from identifiers and code.
  • Translation is a CI pipeline: extraction, TMS with translation memory and MT, human review with context, pseudo-localisation, and versioned bundles on a CDN.
  • Collation affects indexes, uniqueness and upgrades (glibc 2.28). Search needs per-language analysers, CJK segmentation, folding and language detection.
  • Put the locale in the URL or a normalised cache key, never raw Vary: Accept-Language. Use content-hashed bundles and versioned keys for instant translation updates.
  • Locale is not jurisdiction. Data residency follows the user's region or contract, through regional deployments, and includes logs, indexes and caches.