Prompt
How do I add machine translation to a website backend?
Latest observation
Adding machine translation to a website backend usually means: take user/content text, send it to a translation service or model, store/cache the result, and return the translated text in the user’s requested language.
Here’s a practical way to do it.
1) Decide what you’re translating
Common cases:
- User-generated content: comments, posts, messages
- Static site content: pages, product descriptions, help docs
- Dynamic UI strings: labels, buttons, navigation
- Full pages on demand: translate HTML or extracted text
Each case has different tradeoffs:
- UI strings are better handled with i18n files, not MT.
- User content and large text blocks are better suited for machine translation APIs.
2) Choose a translation approach
Option A: Use a cloud translation API
Examples:
- Google Cloud Translation
- DeepL API
- Microsoft Translator
- AWS Translate
Pros:
- Easy to integrate
- Good quality
- Handles many languages
- Scales well
Cons:
- Cost per character/request
- External dependency
- Data/privacy concerns for sensitive text
Option B: Run your own model/service
Examples:
- Open-source models via Hugging Face / MarianMT / NLLB
- Self-hosted translation service
Pros:
- More control
- Potentially lower cost at scale
- Better privacy
Cons:
- More engineering and infrastructure
- Model quality/performance tuning
- GPU/CPU cost
3) Typical backend flow
A good backend architecture looks like this:
- User requests content in language
fr - Backend checks if translation exists in cache/database
- If found, return it
- If not found:
- fetch source text
- call translation service
- store translation
- return translated result
This avoids translating the same text repeatedly.
4) Add language detection
If you don’t already know the source language, detect it first.
You can:
- use a translation API that accepts source auto-detect
- use a separate language detection library/service
Example logic:
- source text is in English
- user wants Spanish
- translate
en -> es
5) Store translations
A common schema:
translations
-------------
id
source_type -- e.g. "post", "comment", "page"
source_id -- ID of original content
source_lang
target_lang
source_text_hash -- to detect when source changes
translated_text
created_at
updated_at
provider -- google/deepl/etc.
Why hash the source text?
- If the original text changes, you know to regenerate the translation.
6) Example backend implementation
Node.js example with a translation API
Pseudo-code:
async function getTranslation(text, sourceLang, targetLang) {
const cacheKey = `${hash(text)}:${sourceLang}:${targetLang}`;
const cached = await db.translations.findOne({ cacheKey });
if (cached) return cached.translatedText;
const translated = await translateApi.translate({
text,
source: sourceLang,
target: targetLang
});
await db.translations.insert({
cacheKey,
sourceLang,
targetLang,
sourceTextHash: hash(text),
translatedText: translated
});
return translated;
}
Python example
def get_translation(text, source_lang, target_lang):
cache_key = f"{hash_text(text)}:{source_lang}:{target_lang}"
cached = db.translations.find_one({"cache_key": cache_key})
if cached:
return cached["translated_text"]
translated = translate_api.translate(
text=text,
source=source_lang,
target=target_lang
)
db.translations.insert_one({
"cache_key": cache_key,
"source_lang": source_lang,
"target_lang": target_lang,
"source_text_hash": hash_text(text),
"translated_text": translated
})
return translated
7) Handle HTML safely
If translating HTML content:
- don’t blindly translate the raw HTML string if the service can’t preserve markup
- extract text nodes, translate only text, then reinsert
- or use a provider that supports HTML input
Be careful with:
- placeholders like
{name} - links, scripts, code blocks
- HTML entities
- line breaks
Best practice:
- mark non-translatable parts
- preserve placeholders exactly
8) Use async jobs for large volumes
If you have many pages or long content:
- queue translation jobs
- return the original content first if needed
- update translations in the background
Tools:
- RabbitMQ
- Redis queues / BullMQ
- Celery
- Sidekiq
- SQS + worker
This avoids slowing down page requests.
9) Fallback strategy
Always define fallback behavior:
- if translation fails, return source text
- log errors
- retry later
- maybe show “translation unavailable”
This keeps your backend reliable.
10) Consider caching and invalidation
Translations should usually be cached because:
- translation is expensive
- repeated requests are common
Invalidate when:
- source content changes
- translation model/provider changes
- language settings change
11) Don’t translate everything
Machine translation is great for:
- content understanding
- broad multilingual support
But avoid using it for:
- legal/medical text without review
- security-sensitive instructions
- user passwords, tokens, or machine-readable config
- brand-critical marketing copy without human review
Sometimes you want:
- human translation for key pages
- MT for long-tail content
- post-editing workflow
12) Minimal architecture recommendation
If you want a straightforward production setup:
- Frontend: user selects language
- Backend API:
/translate?text=...&target=... - Translation provider: DeepL/Google/AWS
- Database cache: store translation results
- Queue worker: pretranslate important content
- Monitoring: log latency, failure rate, cost
13) Security and compliance notes
- Don’t send secrets or PII unless allowed by your provider and policy
- Sanitize inputs
- Rate-limit translation endpoints
- Use API keys securely via environment variables
- Check provider data retention policies
14) If you want to translate a whole website
For full multilingual sites, combine:
- i18n for interface strings
- translation memory / database for content
- locale-based routing like
/en/,/fr/,/es/ - SEO tags:
hreflang- localized URLs
- canonical links
15) Best practice summary
- Use a translation API unless you have strong reasons to self-host
- Cache translations aggressively
- Detect source language
- Translate text, not raw HTML, unless supported
- Use background jobs for scale
- Keep sensitive text out of translation requests when possible
- Combine MT with human review for important content
If you want, I can also show you:
- a full example in Node.js,
- a full example in Python/Django or FastAPI, or
- a database schema + API design for multilingual content.