AWS Builder Center
Tired of Moderating NSFW Content? Let AI Do It for You!

Tired of Moderating NSFW Content? Let AI Do It for You!

A simple demo project showing how to prevent inappropriate content (NSFW) storage without hiring an army of human moderators.

In modern web applications, handling user uploads is a double-edged sword. On one side, you want a seamless experience where images are uploaded, processed, and categorized instantly. On the other side, you face compliance, safety, and security challenges: how do you prevent inappropriate content (NSFW) from reaching your database or other users without hiring an army of human moderators?
To solve this, I built a simple demo serverless, event-driven architecture in AWS that automatically analyzes, tags, and moderates images using AI upon upload. Best of all, the entire infrastructure is defined as code using Terraform, following security best practices.
Here is a look at how this pipeline functions, the security choices made during its development, and how you can deploy it yourself.

The Architecture Overview

The system is designed to be fully event-driven and serverless, meaning zero servers to manage and zero idle costs.
  1. Upload: A user uploads an image to an Amazon S3 source bucket.
  1. Trigger: S3 detects the upload and triggers an AWS Lambda function.
  1. Security Check (Moderation): The Lambda function sends the image to Amazon Rekognition to detect inappropriate content.
  1. Quarantine: If the image contains suggestive or unsafe content, Lambda copies it to a separate, private Quarantine S3 bucket with a prefix  QUARANTINE-  and deletes it from the source bucket. It halts further execution.
  1. AI Tagging: If the image passes security checks, Lambda calls Amazon Rekognition again to extract labels/tags with high confidence.
  1. Data Persistence: The tags, confidence levels, and metadata are written to an Amazon DynamoDB table ( ImageMetadata ) for easy querying later.

A. Security-First Infrastructure with Terraform

Creating this in the AWS console is quick, but managing it via Terraform ensures repeatability and integrates production-ready security standards. Here are the security controls we baked into the Terraform setup:

1. S3 Hardening

By default, S3 buckets are public-facing if not configured carefully. In  s3.tf , we enforced private-only usage:
  • Public Access Blocks: Explicitly enabled  aws_s3_bucket_public_access_block  to block all public ACLs and bucket policies.
  • Server-Side Encryption: Enforced standard  AES256  encryption at rest.
  • Auto-Suffixing: Used a random ID suffix ( random_id ) to prevent bucket namespace collisions.

2. Database Resilience

For DynamoDB, we configured the  ImageMetadata  table with:
  • Point-in-Time Recovery (PITR): Protection against accidental deletes or database corruption.
  • Encryption at Rest: Server-side encryption enabled using AWS-managed keys.
  • On-Demand Billing: Set to  PAY_PER_REQUEST  to automatically scale and avoid provisioned throughput limits.

3. Separation of Configuration (No Hardcoded Secrets)

Rather than hardcoding the quarantine S3 bucket name or the DynamoDB table name into the Lambda function’s source code, we decoupled them. In  lambda.tf , we pass these names dynamically via environment variables:
environment {
variables = {
QUARANTINE_BUCKET = aws_s3_bucket.quarantine_bucket.id
DYNAMODB_TABLE = aws_dynamodb_table.image_metadata.name
}
}

B. Implementing Least-Privilege IAM Policies

A critical pillar of AWS security is the Principle of Least Privilege. We avoid using wildcard permissions ( * ) for our Lambda execution role wherever possible. In our Terraform configurations, we define a custom IAM policy that limits permissions to exactly what the function requires to do its job:
  • CloudWatch Logs: Can only create streams and write logs to its own dedicated Log Group ( /aws/lambda/ImageTaggingFunction ).
  • S3 Source Bucket: Restricted to  s3:GetObject  and  s3:DeleteObject  on the source bucket path.
  • S3 Quarantine Bucket: Restricted to  s3:PutObject  on the quarantine bucket path.
  • DynamoDB: Restricted to  dynamodb:PutItem  on the metadata table ARN.
  • Amazon Rekognition: Granted access to  DetectLabels  and  DetectModerationLabels . (Since Rekognition is a stateless global service, we apply these actions to  * ).
Here is how we define this policy in Terraform ( iam.tf ):
resource "aws_iam_role" "lambda_role" {
name = "image-tagging-lambda-role"

assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}

resource "aws_iam_policy" "lambda_policy" {
name = "image-tagging-lambda-policy"
description = "Least privilege IAM policy for ImageTaggingFunction"

policy = jsonencode({
Version = "2012-10-17"
Statement = [
# CloudWatch Logs (limited to the function's log group name)
{
Effect = "Allow"
Action = [
"logs:CreateLogStream",
"logs:PutLogEvents"
]
Resource = "${aws_cloudwatch_log_group.lambda_log_group.arn}:*"
},
# S3 Source Bucket permissions: Read and Delete (to copy then delete flagged files)
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:DeleteObject"
]
Resource = "${aws_s3_bucket.source_bucket.arn}/*"
},
# S3 Quarantine Bucket permissions: Copy/Write
{
Effect = "Allow"
Action = [
"s3:PutObject"
]
Resource = "${aws_s3_bucket.quarantine_bucket.arn}/*"
},
# DynamoDB Table write permissions
{
Effect = "Allow"
Action = [
"dynamodb:PutItem"
]
Resource = aws_dynamodb_table.image_metadata.arn
},
# Amazon Rekognition permission
{
Effect = "Allow"
Action = [
"rekognition:DetectLabels",
"rekognition:DetectModerationLabels"
]
Resource = "*"
}
]
})
}

resource "aws_iam_role_policy_attachment" "lambda_policy_attach" {
role = aws_iam_role.lambda_role.name
policy_arn = aws_iam_policy.lambda_policy.arn
}

C. Designing the Lambda Logic (Node.js 20.x)

The Lambda handler uses the AWS SDK v3 to coordinate S3, Rekognition, and DynamoDB.
Here is the core logic that executes when S3 triggers the function:
import { RekognitionClient, DetectLabelsCommand, DetectModerationLabelsCommand } from "@aws-sdk/client-rekognition";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import { S3Client, CopyObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";

// Initializing SDK Clients
const rekognitionClient = new RekognitionClient({ region: process.env.AWS_REGION });
const ddbClient = new DynamoDBClient({ region: process.env.AWS_REGION });
const docClient = DynamoDBDocumentClient.from(ddbClient);
const s3Client = new S3Client({ region: process.env.AWS_REGION });

export const handler = async (event) => {
for (const record of event.Records) {
const bucket = record.s3.bucket.name;
const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' '));

try {
// Step 1: Content Moderation Check
const modCommand = new DetectModerationLabelsCommand({
Image: { S3Object: { Bucket: bucket, Name: key } },
MinConfidence: 60
});
const modResponse = await rekognitionClient.send(modCommand);

if (modResponse.ModerationLabels && modResponse.ModerationLabels.length > 0) {
// Suspicious content detected - move to Quarantine
await s3Client.send(new CopyObjectCommand({
Bucket: process.env.QUARANTINE_BUCKET,
CopySource: `${bucket}/${key}`,
Key: `QUARANTINE-${key}`
}));
// Delete from original bucket
await s3Client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
continue;
}

// Step 2: Image Tagging (Safe images only)
const labelCommand = new DetectLabelsCommand({
Image: { S3Object: { Bucket: bucket, Name: key } },
MaxLabels: 5,
MinConfidence: 75
});
const labelResponse = await rekognitionClient.send(labelCommand);
const detailedTags = labelResponse.Labels.map(label => ({
Name: label.Name,
Confidence: parseFloat(label.Confidence.toFixed(2))
}));

// Step 3: Write metadata to DynamoDB
await docClient.send(new PutCommand({
TableName: process.env.DYNAMODB_TABLE,
Item: {
ImageID: key,
Timestamp: new Date().toISOString(),
Analysis: detailedTags,
SourceBucket: bucket
}
}));

} catch (error) {
console.error(`Error processing image ${key}:`, error);
}
}
};
Note: Use the latest Nodejs runtime as it would be better for long run. As this is a demo project, we are using an older version!

D. Verifying the Flow

Once deployed via  terraform apply , we verified the pipeline:
  • Safe Image Upload: Uploaded an image of a golden retreiver dog. The image remained in the source bucket, and DynamoDB was populated with metadata.
  • Moderation Image Upload: Uploaded a suggestive test image, here I had uploaded an image of cigarette. The pipeline immediately deleted the file from the source S3 bucket, renamed it with a  QUARANTINE-  prefix, and placed it in the quarantine S3 bucket. No entry was made in DynamoDB.

Key Takeaways

This project highlights the efficiency of AWS’s serverless offerings when combined with AI:
  • Cost Efficiency: You only pay for what you use (per S3 upload, Lambda execution, and Rekognition scan).
  • Speed to Value: Using Amazon Rekognition means we get state-of-the-art computer vision features without training or maintaining machine learning models ourselves.
  • Security & Repeatability: Wrapping the infrastructure in Terraform ensures that our S3 buckets are locked down, IAM permissions are structured properly, and the entire stack can be recreated in minutes.
How do you handle user-uploaded media in your serverless applications? Let me know in the comments below!
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