How to Use Amazon Translate to Automatically Translate Text in Lambda
When your application starts accepting user-submitted content from multiple regions, the first real-time translation request usually lands in your backlog faster than you expect. Wiring Amazon Translate into a Lambda function for Korean-to-English translation is straightforward, but the details around language code handling, IAM scoping, and response structure are where engineers lose time.
TL;DR: Amazon Translate in Lambda
| Concern | Answer |
|---|---|
| API call for real-time translation | TranslateText via AWS SDK |
| Korean to English language codes | ko → en |
| Auto language detection | Set SourceLanguageCode to auto |
| Max text size per request | Check AWS documentation — limits apply per call |
| IAM action required | translate:TranslateText |
| Synchronous or async | Real-time: synchronous. Batch: asynchronous job API |
How Amazon Translate Works
Amazon Translate is a neural machine translation service. For real-time use cases, you call TranslateText synchronously — the API accepts a text payload, a source language code, and a target language code, then returns the translated string in the same HTTP response. There is no polling or callback involved for this path.
The service also exposes an asynchronous batch translation API (StartTextTranslationJob) for large document sets stored in S3, but that is a separate code path entirely. For user-submitted content translated on the fly, TranslateText is the right primitive.
Language support is expressed through BCP-47 language codes. Korean is ko, English is en. Amazon Translate also supports automatic source language detection — pass auto as the SourceLanguageCode and the service identifies the language before translating. Detection accuracy varies with text length; very short strings can misidentify.
Korean Text"] --> APIGW["API Gateway"] APIGW --> Lambda["Lambda Function
translate_handler"] Lambda --> Translate["Amazon Translate
TranslateText API"] Translate --> Lambda Lambda --> Response["English Text
Response"] Lambda -.->|"optional persist"| Storage["DynamoDB / S3"]
- Client submits Korean text via your API endpoint.
- API Gateway routes the request to a Lambda function.
- Lambda calls
translate:TranslateTextusing the AWS SDK — no VPC or NAT required for the Translate endpoint. - Amazon Translate returns the translated English string synchronously.
- Lambda returns the result to the caller. Optionally persists to DynamoDB or S3.
IAM Permissions for Amazon Translate
The Lambda execution role needs exactly one permission for real-time translation. Keep the resource scope as specific as your use case allows — translate:TranslateText does not support resource-level restrictions, so "Resource": "*" is required here per the Service Authorization Reference.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowRealTimeTranslation",
"Effect": "Allow",
"Action": "translate:TranslateText",
"Resource": "*"
}
]
}
If you enable automatic language detection (SourceLanguageCode: auto), the execution role also needs comprehend:DetectDominantLanguage — Amazon Translate calls Amazon Comprehend internally for detection. Missing this permission causes the auto detection path to fail at runtime with an access denied error, which is easy to miss during development if you test only with explicit language codes.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowRealTimeTranslation",
"Effect": "Allow",
"Action": "translate:TranslateText",
"Resource": "*"
},
{
"Sid": "AllowLanguageDetection",
"Effect": "Allow",
"Action": "comprehend:DetectDominantLanguage",
"Resource": "*"
}
]
}
Calling Amazon Translate from a Lambda Function
The example below uses the AWS SDK for Python (Boto3). The same logical structure applies to Node.js or Java — only the SDK client instantiation and response parsing differ.
🔽 Click to expand — Lambda function (Python, Korean to English)
import boto3
import json
translate_client = boto3.client('translate', region_name='us-east-1')
def lambda_handler(event, context):
# Extract text from the incoming event
source_text = event.get('text', '')
if not source_text:
return {
'statusCode': 400,
'body': json.dumps({'error': 'No text provided'})
}
response = translate_client.translate_text(
Text=source_text,
SourceLanguageCode='ko',
TargetLanguageCode='en'
)
translated_text = response['TranslatedText']
source_language_used = response['SourceLanguageCode']
return {
'statusCode': 200,
'body': json.dumps({
'original': source_text,
'translated': translated_text,
'detectedSourceLanguage': source_language_used
})
}
A few things worth noting in the response object: TranslatedText contains the output string, SourceLanguageCode echoes back what was used (useful when you pass auto), and TargetLanguageCode confirms the target. The SDK raises a ClientError for unsupported language pairs, oversized payloads, or IAM failures — wrap the call in a try/except block in production.
🔽 Click to expand — Lambda function with auto-detection and error handling
import boto3
import json
from botocore.exceptions import ClientError
translate_client = boto3.client('translate', region_name='us-east-1')
def lambda_handler(event, context):
source_text = event.get('text', '')
if not source_text:
return {
'statusCode': 400,
'body': json.dumps({'error': 'No text provided'})
}
try:
response = translate_client.translate_text(
Text=source_text,
SourceLanguageCode='auto',
TargetLanguageCode='en'
)
except ClientError as e:
error_code = e.response['Error']['Code']
return {
'statusCode': 500,
'body': json.dumps({
'error': error_code,
'message': e.response['Error']['Message']
})
}
return {
'statusCode': 200,
'body': json.dumps({
'original': source_text,
'translated': response['TranslatedText'],
'detectedSourceLanguage': response['SourceLanguageCode']
})
}
Deploying and Testing the Lambda Function via CLI
These commands assume you have already packaged your function code as a ZIP file and created the IAM execution role. Replace the role ARN and region with your actual values.
# Create the Lambda function
aws lambda create-function \
--function-name translate-korean-to-english \
--runtime python3.12 \
--role arn:aws:iam::123456789012:role/TranslateLambdaRole \
--handler lambda_function.lambda_handler \
--zip-file fileb://function.zip \
--region us-east-1
# Invoke the function with a test payload
aws lambda invoke \
--function-name translate-korean-to-english \
--payload '{"text": "안녕하세요, 오늘 날씨가 좋네요."}' \
--cli-binary-format raw-in-base64-out \
--region us-east-1 \
response.json
cat response.json
The --cli-binary-format raw-in-base64-out flag is required for AWS CLI v2 when passing a raw JSON string as the payload. Omitting it causes a base64 decode error — a common stumble on first invocation.
Supported Languages and Language Codes
Amazon Translate supports a broad set of languages. The following are commonly used pairs for applications handling East Asian and European content. For the full current list, always verify against the Amazon Translate supported languages documentation — the supported set expands over time and language pair support is not always symmetric.
| Language | Code | Notes |
|---|---|---|
| Korean | ko | Supported as source and target |
| English | en | Supported as source and target |
| Japanese | ja | Supported as source and target |
| Chinese (Simplified) | zh | Supported as source and target |
| Chinese (Traditional) | zh-TW | Supported as source and target |
| Spanish | es | Supported as source and target |
| French | fr | Supported as source and target |
| German | de | Supported as source and target |
| Auto-detect | auto | Source only — requires Comprehend permission |
Not all language pairs translate directly through a single neural model. Some pairs route through an intermediate pivot language (typically English) internally. This is transparent to the caller but can affect translation quality for non-English pivot pairs. Check the documentation for your specific pair if quality is a concern.
A Real Failure Pattern: The Missing Comprehend Permission
Here is a failure sequence that shows up regularly in production setups: the function works perfectly in development because the developer tests with SourceLanguageCode: 'ko' explicitly. The IAM policy is scoped to translate:TranslateText only. Everything passes code review.
Then someone updates the code to use auto detection to handle multilingual input. The Lambda function starts returning 500 errors in production. CloudWatch logs show an AccessDeniedException — but the error message references comprehend:DetectDominantLanguage, not translate:TranslateText. Engineers spend time checking the Translate IAM policy, which is correct, before realizing the Comprehend action is missing entirely.
The fix is the two-statement IAM policy shown earlier. The diagnostic is straightforward once you know to look at Comprehend — but the error message alone does not make the connection obvious if you did not know Amazon Translate delegates detection internally.
WhenSourceLanguageCodeis set toauto, Amazon Translate calls Amazon Comprehend on your behalf using your execution role's credentials. The Comprehend permission is not optional — it is a hard requirement for that code path.
Scaling Considerations for High-Volume Translation
For user-submitted content at low-to-moderate volume, synchronous Lambda invocation works well. At higher throughput, a few operational patterns matter:
- Concurrency limits: Lambda concurrency and Amazon Translate throughput quotas are separate constraints. If your Lambda scales aggressively, you may hit Translate service quotas before Lambda limits. Check current quotas in the AWS Service Quotas console and request increases proactively.
- Text chunking: Amazon Translate enforces a maximum text size per
TranslateTextcall. For user-submitted content that may exceed this, implement chunking logic in Lambda before calling the API. Pricing and limits vary — check the official AWS documentation. - Caching repeated translations: If your application translates the same content repeatedly (product descriptions, static UI strings), caching translated results in ElastiCache or DynamoDB reduces both latency and cost. The Translate API is stateless — it does not cache on your behalf.
- Check cache first — if a translation for this text+language pair already exists, return it immediately without calling Translate.
- Chunk if needed — if the text exceeds the API size limit, split into segments, translate each, then reassemble.
- Call TranslateText — synchronous API call with source and target language codes.
- Store result — persist the translation to cache for future requests before returning to the caller.
Wrap-Up and Next Steps for Amazon Translate Integration
The core integration is minimal: one IAM action, one SDK call, one response field. The operational complexity lives in language detection permissions, text size handling, and throughput planning — not in the API itself.
For next steps:
- Review the Amazon Translate Developer Guide for current language pair support and quota details.
- If you need to translate documents (PDF, DOCX) rather than raw text, explore the
StartTextTranslationJobbatch API with S3 input/output. - For custom terminology (brand names, product names that should not be translated), look at Amazon Translate Custom Terminology — it lets you define term overrides applied at translation time.
- Monitor translation costs with AWS Cost Explorer tagged by Lambda function to understand per-feature spend as volume grows.
Glossary
| Term | Definition |
|---|---|
| TranslateText | The synchronous Amazon Translate API action for real-time text translation. |
| BCP-47 | The language tag standard used by Amazon Translate for language codes (e.g., ko, en, zh-TW). |
| Auto-detection | Passing auto as SourceLanguageCode to let Amazon Translate identify the source language via Amazon Comprehend. |
| Custom Terminology | An Amazon Translate feature that lets you define term-level translation overrides applied consistently across all translations. |
| Execution Role | The IAM role assumed by a Lambda function at runtime, whose permissions govern all AWS API calls the function can make. |
Comments
Post a Comment