Building a Real-Time Comment Sentiment Analysis Pipeline on AWS with Comprehend

Learn how to automate user feedback classification by building a serverless comment analysis pipeline using Amazon Comprehend, AWS Lambda, and Amazon DynamoDB to extract sentiment and key phrases.

Understanding user feedback at scale is critical for any modern application, but manually reviewing thousands of comments is slow and inconsistent. By combining serverless compute with managed Natural Language Processing (NLP), you can automatically classify user comments into positive, negative, neutral, or mixed sentiments in real time.
In this article, we will walk through an event-driven architecture on AWS that ingests user comments, analyzes their tone and key themes using **Amazon Comprehend**, and stores the structured insights for downstream analytics.
---
## Architecture Overview
The pipeline relies on four core AWS services to keep operational overhead low and scaling automatic:
1. **Amazon API Gateway:** Exposes a REST endpoint to receive incoming comment payloads from your web or mobile frontend. 2. **AWS Lambda:** Processes the incoming JSON payload, invokes the NLP model, and formats the response. 3. **Amazon Comprehend:** Detects the dominant sentiment (`POSITIVE`, `NEGATIVE`, `NEUTRAL`, `MIXED`), confidence scores, and key phrases without requiring custom ML model training. 4. **Amazon DynamoDB:** Persists the raw comment alongside its sentiment metadata for fast querying and dashboarding.
---
## Step 1: Processing Comments with AWS Lambda
Once a user submits a comment through API Gateway, an AWS Lambda function handles the orchestration. Below is a Python example using `boto3` to extract both sentiment and key phrases:
```python import json import uuid import boto3 from datetime import datetime, timezone
comprehend = boto3.client('comprehend') dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('CommentAnalysisResults')
def lambda_handler(event, context): body = json.loads(event.get('body', '{}')) comment_text = body.get('comment', '').strip()
if not comment\_text:
return \{
'statusCode': 400,
'body': json.dumps(\{'error': 'Comment text is required'})
}

\# Detect sentiment
sentiment\_response = comprehend.detect\_sentiment(
Text=comment\_text,
LanguageCode='en'
)

\# Extract key phrases
phrases\_response = comprehend.detect\_key\_phrases(
Text=comment\_text,
LanguageCode='en'
)
key\_phrases = \[p\['Text'] for p in phrases\_response\['KeyPhrases']]

item = \{
'comment\_id': str(uuid.uuid4()),
'timestamp': datetime.now(timezone.utc).isoformat(),
'comment': comment\_text,
'sentiment': sentiment\_response\['Sentiment'],
'confidence\_scores': \{
k: str(round(v, 4)) for k, v in sentiment\_response\['SentimentScore'].items()
},
'key\_phrases': key\_phrases
}

table.put\_item(Item=item)

return \{
'statusCode': 200,
'body': json.dumps(item)
}
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article