0% found this document useful (0 votes)
5 views53 pages

AWS Java Interview Guide - MD

The document is an interview preparation guide for AWS Java Full-Stack Developers, covering key topics such as compute services, API management, database services, security, and deployment strategies. It includes detailed sections on AWS services like EC2, ECS, EKS, Lambda, RDS, and DynamoDB, along with interview questions and answers for each topic. The guide emphasizes best practices, common patterns, and essential concepts relevant to Java applications on AWS.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views53 pages

AWS Java Interview Guide - MD

The document is an interview preparation guide for AWS Java Full-Stack Developers, covering key topics such as compute services, API management, database services, security, and deployment strategies. It includes detailed sections on AWS services like EC2, ECS, EKS, Lambda, RDS, and DynamoDB, along with interview questions and answers for each topic. The guide emphasizes best practices, common patterns, and essential concepts relevant to Java applications on AWS.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

AWS Java Full-Stack Developer - Interview Preparation Guide

Table of Contents
1. Compute Services
2. API Management
3. Database Services
4. Security & Access Control
5. Frontend Deployment
6. CI/CD Pipelines
7. Containerization & Orchestration
8. Monitoring & Observability
9. Architecture Patterns
10. Interview Questions & Answers

Compute Services
EC2 (Elastic Compute Cloud)
What It Is:
Virtual servers (instances) that you can launch and manage
Flexible sizing with on-demand, reserved, and spot pricing models
Full control over OS, application stack, and networking

Key Concepts for Java:


Instance types: General purpose (t3, m5), Compute optimized (c5), Memory
optimized (r5)
AMIs (Amazon Machine Images): Pre-configured templates with Java, app servers
Security groups: Act as virtual firewalls controlling inbound/outbound traffic
Elastic IPs: Static public IPs that persist across restarts
Auto Scaling Groups: Automatically scale instances based on demand metrics

Java Application Use Cases:


Traditional monolithic Spring Boot applications
Custom application server deployments (Tomcat, JBoss)
Baseline for understanding other compute options

Pros & Cons:


✅ Maximum control and flexibility
✅ Suitable for legacy applications
✅ No vendor lock-in for application design
❌ Requires manual infrastructure management
❌ Higher operational overhead for teams
❌ Need to manage OS patching and updates
Interview Focus:
How would you scale a Java application on EC2?
What's the difference between instance types and when to use each?
How do security groups relate to network architecture?

ECS (Elastic Container Service)


What It Is:
Managed container orchestration service for Docker containers
Two launch types: EC2 and Fargate
Integrates with Docker registries (ECR, Docker Hub)

Key Concepts:
Task Definition: JSON file defining container specs (image, CPU, memory,
environment variables, port mappings)
Task: Running instance of a task definition
Service: Long-running tasks with auto-scaling and load balancing
Cluster: Logical grouping of resources (EC2 instances or Fargate capacity)

ECS vs Fargate:

Aspect ECS on EC2 ECS Fargate

Infrastructure You manage EC2 instances AWS manages servers

Scaling Manual EC2 + auto-scaling groups Automatic based on task definition

Cost Lower cost for sustained workloads Higher per-task cost, pay-as-you-go

Control Full OS access Limited, container-level only

Best For Predictable, high-volume loads Variable loads, bursty traffic


Java on ECS:

Common patterns:
1. Spring Boot containerized → Fargate service → ALB → RDS
2. Multi-container microservices (logging, metrics sidecars)
3. Batch jobs scheduled via CloudWatch Events

Interview Focus:
How do you configure health checks in ECS?
What's the difference between task placement strategies?
How would you implement zero-downtime deployments in ECS?

EKS (Elastic Kubernetes Service)


What It Is:
Managed Kubernetes service
Abstracts control plane management
You manage worker nodes (or use Fargate)

Key Concepts:
Pods: Smallest deployable units (usually one container per pod)
Deployments: Manage replicas and rolling updates
Services: Expose pods internally or externally
ConfigMaps & Secrets: Configuration and sensitive data
Ingress: External HTTP/HTTPS routing
StatefulSets: For stateful applications (databases, caches)

Java on EKS:
Spring Boot microservices with automatic scaling
Service discovery via DNS (e.g., [Link] )
Pod autoscaling based on CPU/memory metrics
Volume mounts for persistent storage (EBS, EFS)

When to Choose EKS:


✅ Microservices architecture
✅ Need advanced scheduling and orchestration
✅ Multi-cloud flexibility (Kubernetes is portable)
✅ Complex networking requirements
❌ Steeper learning curve than ECS
❌ More operational overhead
Interview Focus:
What's the difference between Deployments and StatefulSets?
How does service discovery work in Kubernetes?
Explain rolling updates and canary deployments in Kubernetes
How would you implement blue-green deployments with Kubernetes?

AWS Lambda
What It Is:
Serverless compute: Pay only for execution time
Auto-scales from zero to thousands of concurrent executions
Stateless function execution

Java on Lambda:
Cold starts: Java has slower cold starts than [Link]/Python (1-2 seconds typical)
GraalVM native images: Reduce cold start time (100-200ms)
Quarkus/Micronaut: Optimized frameworks for Lambda
Handler functions: Entry point for Lambda execution

Common Java Lambda Patterns:

1. API Gateway trigger → Lambda → RDS/DynamoDB


2. S3 events → Lambda (image processing, thumbnail generation)
3. SNS/SQS → Lambda (async processing, event-driven)
4. Scheduled (CloudWatch Events) → Lambda (batch jobs)
5. DynamoDB Streams → Lambda (event-driven data pipelines)

Considerations:
Memory: 128MB-10,240MB (affects CPU allocation)
Timeout: Default 3 seconds, max 15 minutes
Concurrency limits: Default 1,000 concurrent executions per account
Packaging: JAR files typically 50MB+ (larger than other runtimes)

Interview Focus:
How would you design for cold starts with Java Lambda?
When would you choose Lambda vs ECS/EKS for a microservice?
How do you structure a Lambda handler with dependency injection?
What are provisioned concurrency and when would you use it?

API Management
API Gateway
What It Is:
Fully managed API service
Create, publish, maintain, monitor, secure APIs
Multiple endpoint types: REST APIs, HTTP APIs, WebSocket APIs

Key Features:
Request/Response Transformation: Map incoming requests to backend format
Authorization: API keys, Lambda authorizers, JWT validation, Cognito
Rate Limiting & Throttling: Protect backend from overload
CORS: Enable cross-origin requests for frontend apps
Caching: Cache responses to reduce backend calls
Stages: dev, staging, prod with separate configurations
Logging: CloudWatch integration for debugging

API Gateway vs ALB:

Feature API Gateway ALB

Layer Application (L7) Transport + Application (L4/L7)

Best For Microservices, serverless Traditional load balancing

Auth Built-in (Cognito, Lambda) External (must implement)

Caching Built-in Need CloudFront

Cost Per request + data transfer Per LCU (load balancer capacity unit)

Setup Simpler API setup More infrastructure setup

Typical Flow:
Angular/React Frontend → API Gateway → Lambda/ECS/EC2 Backend

Authorization check
Request validation
Rate limiting

Interview Focus:
How would you implement request validation in API Gateway?
Explain API Gateway stages and stage variables
How do Lambda authorizers work and when would you use them?
What's the difference between REST APIs and HTTP APIs?

Application Load Balancer (ALB)


What It Is:
Layer 7 (application layer) load balancer
Routes based on hostname, path, HTTP headers
Better for microservices and content-based routing

Key Features:
Path-based routing: /api/v1/* → Service A, /images/* → Service B
Hostname-based routing: [Link] → Service A, [Link] →
Service B
Host headers and HTTP methods: Fine-grained routing rules
Sticky sessions: Session affinity based on duration or cookie
Health checks: Target group health monitoring
SSL/TLS termination: Decrypt HTTPS traffic

Java Applications with ALB:

ALB listens on port 80/443



Routes to Target Groups (EC2 instances, ECS tasks, Lambda)

Each target runs Java application (port 8080, 8081, etc.)

Health Check Configuration:


Path: /health or /actuator/health (Spring Boot)
Interval: 30 seconds
Timeout: 5 seconds
Healthy threshold: 2 consecutive successes
Unhealthy threshold: 2 consecutive failures

Interview Focus:
How do you configure path-based routing with an ALB?
What makes a target unhealthy and how are requests handled?
How would you implement sticky sessions and when?
Difference between ALB and Network Load Balancer (NLB)?

Database Services
RDS (Relational Database Service)
What It Is:
Managed relational database service
Supports: MySQL, PostgreSQL, MariaDB, Oracle, SQL Server
Handles backups, patches, failover automatically

Key Concepts:
Multi-AZ Deployments: Synchronous replication to standby instance
Automatic failover if primary fails
~1-2 minute failover time
Double cost but high availability
Read Replicas: Asynchronous replication for read scaling
Can be in different regions (for DR)
Can promote replica to standalone database
No automatic failover
Storage Tiers: General Purpose (gp2, gp3), Provisioned IOPS
gp3: Latest, good for most workloads
gp2: Previous generation, still common
io1/io2: High I/O requirements
Backups:
Automated: Retained 1-35 days
Manual: Retained indefinitely
Restore to point-in-time (within backup window)

Java Integration:

Spring Boot Application



HikariCP Connection Pool (JDBC)

RDS PostgreSQL/MySQL

Network: Security group must allow inbound on DB port

Performance Tuning:
Connection Pooling: HikariCP settings (pool size, max lifetime, idle timeout)
Query Optimization: Use EXPLAIN ANALYZE
Indexing: Strategic indexes on frequently queried columns
Parameter Store: Store connection details securely
Monitoring: RDS CloudWatch metrics (CPU, storage, connections, latency)

Common Issues:
Too many connections: Tune pool size
Slow queries: Identify with CloudWatch logs, optimize
Storage full: Auto-scaling storage in RDS
Replication lag with read replicas

Interview Focus:
When would you use Multi-AZ vs Read Replicas?
How do you handle database migration to RDS?
What's connection pooling and why is it important?
How would you debug a slow query in RDS?

DynamoDB
What It Is:
Fully managed NoSQL database
Key-value and document store
Automatic scaling with on-demand or provisioned capacity

Key Concepts:
Data Model:
Tables: Similar to tables in SQL
Items: Similar to rows (can have different attributes)
Attributes: Similar to columns (schema-less)
Primary Key:
Partition Key (hash): Determines which partition
Sort Key (range): Optional, determines order within partition
Together: Must be unique

Example:

Table: Orders
Items:
{
customerId (Partition Key): "cust-123",
orderId (Sort Key): "order-456",
timestamp: 1625097600,
items: [... product list ...],
total: 99.99
}

Capacity Modes:
Provisioned: You specify read/write capacity units
RCU: One strongly consistent read of up to 4KB/second
WCU: One write of up to 1KB/second
More predictable costs
On-Demand: Pay per request
No capacity planning
More expensive at scale
Good for variable workloads

Advanced Features:
Indexes:
Global Secondary Index (GSI): Different partition key, eventual consistency
Local Secondary Index (LSI): Same partition key, different sort key, strong
consistency
Use for alternative query patterns
DynamoDB Streams: Ordered stream of item modifications
Trigger Lambda functions
Replicate to other databases
TTL (Time To Live): Automatic item deletion
Set on an attribute
Items deleted within 48 hours

Performance Optimization:
Hot Partitions: Avoid concentrating writes on few partition keys
Sort Key Design: Use composite sort keys for range queries
Projection: Return only needed attributes to save RCU
Batch Operations: BatchGetItem, BatchWriteItem for efficiency
Query vs Scan: Always use Query over Scan when possible

Java Integration:

DynamoDB SDK ([Link]:enhanced-client)



Table annotations (@DynamoDbBean, @DynamoDbPartitionKey)

Methods: putItem, getItem, query, scan, updateItem, deleteItem

Consistency Models:
Strong Consistency: Read always latest data (more latency, more RCU)
Eventual Consistency: May read stale data (less latency, less RCU)
Use strong consistency for critical reads (banking, inventory)

Interview Focus:
Design a DynamoDB schema for a social media app (users, posts, followers)
When would you use GSI vs LSI?
How would you handle hot partitions?
What's the difference between Query and Scan?
How do you implement pagination with Query?

Security & Access Control


IAM (Identity and Access Management)
Core Components:
Users: Individual AWS accounts
Roles: Assumed by services or other accounts
Policies: JSON documents defining permissions
Groups: Collection of users with same permissions

Policy Structure:

json

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*",
"Condition": {
"StringEquals": {
"aws:SourceVpc": "vpc-12345"
}
}
}
]
}

Best Practices:
Principle of Least Privilege: Grant minimum necessary permissions
Role-based access: Use roles for EC2, Lambda, ECS rather than access keys
No hardcoded credentials: Use temporary credentials from STS
MFA: Enable for root account and important users
Policy conditions: Restrict by IP, time, VPC, etc.

Common IAM Roles for Java Applications:


EC2 Instance Role:
- Read from S3 (application assets)
- Write to CloudWatch Logs
- Access RDS through VPC
- Access DynamoDB
- Get secrets from Secrets Manager

Lambda Execution Role:


- Write to CloudWatch Logs (always required)
- Access DynamoDB, RDS
- Call other AWS services
- Get environment variables from Parameter Store

Interview Focus:
Design IAM roles for a Java microservices architecture
What's the difference between Users and Roles?
How do you securely manage AWS credentials in applications?
Explain resource-based policies vs identity-based policies

Amazon Cognito
What It Is:
User authentication and authorization service
Managed user pools and identity pools
OpenID Connect and SAML integration

Key Components:
User Pools: Manage user authentication (signup, signin, MFA)
Identity Pools: Provide temporary AWS credentials to access services
App Clients: OAuth 2.0 application integration

Typical Flow:

1. User signs in with email/password → Cognito User Pool


2. Cognito returns JWT tokens (ID token, Access token)
3. Frontend sends JWT in Authorization header
4. Backend validates JWT (using public keys)
5. Optionally: Exchange JWT for temporary AWS credentials via Identity Pool

JWT Tokens:
ID Token: User identity information (name, email, custom attributes)
Access Token: Used to access protected resources
Refresh Token: Used to get new ID/Access tokens

Integration with Spring Boot:

Spring Security

@EnableWebSecurity + JwtAuthenticationConverter

Validate JWT signature using Cognito public keys

Extract user claims for authorization

Interview Focus:
Explain the Cognito user pool signup/signin flow
What's the difference between User Pools and Identity Pools?
How do you validate JWT tokens from Cognito?
How would you implement multi-factor authentication?

VPCs and Security Groups


VPC (Virtual Private Cloud):
Virtual network isolated from other networks
Control over IP addressing, subnets, routing
Essential for network security and isolation

Subnets:
Public Subnet: Has route to Internet Gateway
Instances need public IP or Elastic IP to access internet
Good for load balancers, NAT gateways
Private Subnet: No direct internet access
Only internal communication
Access internet through NAT gateway in public subnet
Good for databases, application servers

Network Architecture Example:


Internet

Internet Gateway

Public Subnet: ALB ([Link]/0 ingress on 80, 443)

Private Subnet: ECS/EC2 (Ingress only from ALB security group)

Private Subnet: RDS (Ingress only from ECS security group on port 3306/5432)

Security Groups:
Stateful: If you allow outbound, return traffic is automatically allowed
Rules: Specify source/destination IP, protocol, port
Best Practice: Allow only what's needed

Interview Focus:
Design a VPC for a Java application
What's the difference between Security Groups and Network ACLs?
Why use private subnets for databases?
How do private subnets access the internet?

Secrets Manager & Parameter Store


Secrets Manager:
Store sensitive data (database passwords, API keys)
Automatic rotation for supported services
Encryption with KMS
Cost: Per secret per month + per API call

Parameter Store:
Store configuration data and secrets
Free tier available
Simpler than Secrets Manager
No automatic rotation (but can implement via Lambda)

Java Integration:
Spring Boot Application

AWS SDK v2: [Link]:secretsmanager

Retrieve at startup: [Link](request)

Parse JSON and populate environment/configuration

Best Practice:

RDS Password → Secrets Manager (with rotation)


API Keys → Secrets Manager
Configuration (region, endpoints) → Parameter Store
Feature flags → Parameter Store

Interview Focus:
When would you use Secrets Manager vs Parameter Store?
How do you implement automatic secret rotation?
How would you refresh secrets in a running application?

Frontend Deployment
S3 + CloudFront
S3 (Simple Storage Service):
Object storage service
Bucket versioning, lifecycle policies, encryption
Can host static websites (HTML, CSS, JS)

S3 Static Website Hosting:

1. Create bucket
2. Enable static website hosting
3. Upload React/Angular build artifacts ([Link], [Link], etc.)
4. Configure bucket policy to allow public read (optional, use CloudFront
instead)
5. Access via bucket website endpoint

CloudFront (CDN):
Content Delivery Network
Caches content at edge locations globally
Serves from location closest to user
Reduces latency and origin server load
Distribution Setup:

Origin: S3 bucket or API Gateway



CloudFront Distribution

Behaviors:
- /api/* → API Gateway origin (no caching)
- /images/* → S3 origin (cache 24 hours)
- /* → S3 origin (cache based on headers)

Edge locations cache and serve to users

Caching Strategy:
Cache Control Headers: Set via S3 metadata
[Link]: Cache-Control: max-age=0 (always revalidate)
[Link]: Cache-Control: max-age=31536000 (1 year, with versioning)
images: Cache-Control: max-age=86400 (1 day)

CloudFront Features:
Origins: S3, ALB, API Gateway, custom HTTP servers
Behaviors: Different caching rules per path
Invalidation: Purge cache immediately (costs money, use sparingly)
Geo-restriction: Restrict access by country
HTTPS: Free SSL/TLS certificate with CloudFront
Origin Shield: Extra cache layer for origin protection

Environment Configuration:

Development:
- Direct S3 endpoint or CloudFront
- Point to dev API Gateway

Production:
- CloudFront distribution
- Custom domain via Route 53
- Point to prod API Gateway
- Security headers (CSP, X-Frame-Options)
Interview Focus:
How would you deploy a React app with multiple environments?
Explain cache invalidation strategies
When would you use CloudFront vs serving directly from S3?
How do you handle environment variables in a static Angular app?

CI/CD Pipelines
AWS CodePipeline
What It Is:
Managed CI/CD orchestration service
Coordinates source, build, deploy stages
Integrates with CodeBuild, CodeDeploy, and third-party tools

Pipeline Stages:

Source (GitHub, CodeCommit)



Build (CodeBuild: compile, test, build Docker image)

Test (Optional: Run integration tests)

Deploy (ECS, EC2, Lambda, Elastic Beanstalk)

Manual Approval (Optional: before prod)

Production Deployment

Typical Java Pipeline:


GitHub Push

CodePipeline triggered

CodeBuild:
- Checkout code
- Run Maven/Gradle build
- Run unit tests
- Run integration tests
- Build Docker image
- Push to ECR

CodeDeploy/ECS Update:
- Update ECS service with new image
- Rolling update (preserve running tasks)
- Health checks ensure healthy task before removing old

CloudWatch monitoring
- Monitor error rates, logs

GitHub Actions
Alternative to CodePipeline:
Runs directly on GitHub
YAML workflow files in .github/workflows/
Free for public repos, included with GitHub

Example Workflow:

yaml
name: Build and Deploy
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK
uses: actions/setup-java@v2
with:
java-version: '11'
- name: Build with Maven
run: mvn clean package
- name: Build Docker image
run: docker build -t my-app:${{ [Link] }} .
- name: Push to ECR
run: |
aws ecr get-login-password | docker login --username AWS --password-s
docker push $ECR_REGISTRY/my-app:${{ [Link] }}
- name: Update ECS service
run: |
aws ecs update-service \
--cluster prod \
--service my-app-service \
--force-new-deployment

CodeBuild
What It Is:
Managed build service
Runs Docker containers with build environment
Supports Java, Python, [Link], .NET, etc.

[Link]:

yaml
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to ECR...
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login
build:
commands:
- echo Build started on `date`
- mvn clean package -DskipTests
- docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
- docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.[Link].$AWS_DEF
post_build:
commands:
- echo Build completed on `date`
- docker push $AWS_ACCOUNT_ID.[Link].$AWS_DEFAULT_REGION.[Link]/$
artifacts:
files:
- [Link]

Jenkins
On-Premises/Self-Hosted:
Full control over pipeline
Integration with AWS via plugins
Common for enterprise environments

Pipeline Stages:

groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Push to ECR') {
steps {
sh '''
aws ecr get-login-password | docker login --username AWS --password-s
docker build -t my-app:${BUILD_NUMBER} .
docker push $AWS_ACCOUNT_ID.[Link].$AWS_DEFAULT_REGION.[Link]
'''
}
}
stage('Deploy to ECS') {
steps {
sh '''
aws ecs update-service --cluster prod --service my-app-service --forc
'''
}
}
}
}

Interview Focus:
Design a complete CI/CD pipeline for a Java microservices application
How would you implement canary deployments?
What's the difference between CodePipeline and GitHub Actions?
How do you handle secrets (database passwords, API keys) in CI/CD?
What metrics would you monitor in a deployment pipeline?

Containerization & Orchestration


Docker
Dockerfile for Java Spring Boot:

dockerfile
# Multi-stage build for smaller image
FROM maven:3.8-openjdk-11 AS builder
WORKDIR /app
COPY . .
RUN mvn clean package -DskipTests

FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=builder /app/target/[Link] [Link]
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f [Link] || exit 1
ENTRYPOINT ["java", "-jar", "[Link]"]

Optimization:
Multi-stage builds: Reduce final image size (smaller = faster deployment)
Base image: Use -slim or -alpine variants
Layer caching: Put changes near end of Dockerfile
.dockerignore: Exclude unnecessary files

Docker Compose (for local development):

yaml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://postgres:5432/mydb
- SPRING_DATASOURCE_USERNAME=postgres
- SPRING_DATASOURCE_PASSWORD=password
depends_on:
- postgres
postgres:
image: postgres:13
environment:
POSTGRES_DB: mydb
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:

EKS Deep Dive


Architecture:

Control Plane (AWS managed):


- API Server
- Scheduler
- Controller Manager

Worker Nodes (you manage):


- Kubelet
- Container Runtime (Docker, containerd)
- kube-proxy

Communication:
- Nodes register with API Server
- Control plane sends commands to nodes

Deployments & ReplicaSets:

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: java-app
spec:
replicas: 3
selector:
matchLabels:
app: java-app
template:
metadata:
labels:
app: java-app
spec:
containers:
- name: java-app
image: my-registry/java-app:1.0.0
ports:
- containerPort: 8080
resources:
requests:
memory: "512Mi"
cpu: "250m"
limits:
memory: "1Gi"
cpu: "500m"
livenessProbe:
httpGet:
path: /actuator/health
port: 8080
initialDelaySeconds: 15
periodSeconds: 20
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 5
periodSeconds: 10

Services & Ingress:

yaml
# Service: Internal DNS and load balancing
apiVersion: v1
kind: Service
metadata:
name: java-app
spec:
type: ClusterIP # Internal only
selector:
app: java-app
ports:
- protocol: TCP
port: 80
targetPort: 8080

---

# Ingress: External routing


apiVersion: [Link]/v1
kind: Ingress
metadata:
name: java-app-ingress
annotations:
[Link]/[Link]: alb
[Link]/scheme: internet-facing
spec:
rules:
- host: [Link]
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: java-app
port:
number: 80

StatefulSets (for stateful applications):

yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: database
spec:
serviceName: database
replicas: 3
selector:
matchLabels:
app: database
template:
metadata:
labels:
app: database
spec:
containers:
- name: database
image: postgres:13
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi

Autoscaling:

yaml
# Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: java-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: java-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80

Interview Focus:
Design a Kubernetes deployment for a microservices application
Explain liveness and readiness probes
How do you implement blue-green deployment in Kubernetes?
What's the difference between DaemonSets and Deployments?
How do you manage environment-specific configurations?

Monitoring & Observability


CloudWatch
Metrics:
System metrics (EC2 CPU, network, disk)
Application metrics (custom metrics)
Service metrics (API Gateway latency, Lambda duration)
Default: 1-minute granularity (can reduce to 1-second for cost)
CloudWatch Agent (for EC2):

json
{
"metrics": {
"namespace": "MyApplication",
"metrics_collected": {
"cpu": {
"measurement": [
{
"name": "cpu_usage_idle",
"rename": "CPU_IDLE",
"unit": "Percent"
}
],
"totalcpu": false,
"metrics_collection_interval": 60
},
"mem": {
"measurement": [
{
"name": "mem_used_percent",
"rename": "MEM_USED",
"unit": "Percent"
}
],
"metrics_collection_interval": 60
},
"disk": {
"measurement": [
{
"name": "used_percent",
"rename": "DISK_USED",
"unit": "Percent"
}
],
"metrics_collection_interval": 60,
"resources": ["/"]
}
}
},
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{
"file_path": "/var/log/[Link]",
"log_group_name": "/aws/ec2/app",
"log_stream_name": "{instance_id}"
}
]
}
}
}
}

Logs:
Centralized logging from EC2, Lambda, ECS, RDS
Log Groups: /aws/lambda/function-name , /aws/ecs/service-name
Log Streams: Organized by source (container, instance, etc.)
Retention: Configure per log group

Java Application Logging:

Spring Boot + Logback



JSON formatted logs

CloudWatch Logs agent

CloudWatch Logs group

CloudWatch Insights for querying

CloudWatch Insights Queries:

# Find errors in last hour


fields @timestamp, @message
| filter @message like /ERROR/
| stats count() by @message

# Latency percentiles
fields @duration
| stats pct(@duration, 50), pct(@duration, 95), pct(@duration, 99)

# Request rate by endpoint


fields @httpMethod, @path
| stats count() as requests by @path, @httpMethod

Alarms:
Threshold-based: CPU > 80%, Error rate > 1%
Composite alarms: Multiple conditions (AND, OR)
Actions: SNS notifications, Auto Scaling, EC2 actions
Example Alarms:

High Error Rate:


- Metric: 5xx errors from ALB target group
- Threshold: > 5% for 2 minutes
- Action: SNS topic (PagerDuty, Slack)

High Latency:
- Metric: ALB target response time
- Threshold: > 1000ms (p95) for 5 minutes
- Action: Scale up Auto Scaling group

RDS Connection Exhaustion:


- Metric: Database connections
- Threshold: > 90% of max for 1 minute
- Action: SNS + manual intervention

Distributed Tracing (X-Ray)


What It Is:
Distributed tracing to understand application flow
Shows latency bottlenecks across services
Visual service map

Java Integration:

xml

<dependency>
<groupId>[Link]</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-core</artifactId>
</dependency>

Configuration:

java
import [Link];
import [Link];
import [Link];

@Configuration
public class XRayConfig {
@Bean
public Filter TracingFilter() {
return new AWSXRayServletFilter("MyApp");
}
}

Service Map:

Frontend (API Gateway) → Backend (Lambda) → RDS



DynamoDB

S3 (get config)

Interview Focus:
How would you set up monitoring for a Java microservices application?
What metrics would you alert on?
Explain centralized logging and structured logging
How do you implement distributed tracing?

Architecture Patterns
Microservices Architecture
Benefits:
Independent scaling
Technology diversity
Fault isolation
Faster deployment cycles

Challenges:
Distributed debugging
Network latency
Data consistency
Operational complexity
Typical Structure:

API Gateway → Service Mesh (Istio/AWS App Mesh)



Microservices:
- User Service (Spring Boot) → PostgreSQL
- Order Service (Spring Boot) → PostgreSQL + DynamoDB
- Payment Service (Spring Boot) → External API

Communication:
- Synchronous: REST APIs
- Asynchronous: SNS/SQS, Event Streaming

Observability:
- CloudWatch Logs
- X-Ray tracing
- Prometheus metrics

Service Communication Patterns:


1. Request-Response:
Service A → Service B (HTTP/gRPC)
Synchronous, tight coupling
Good for immediate feedback
2. Event-Driven:
Service A publishes event → SNS
SNS → SQS for Service B
Service B processes asynchronously
Loose coupling, eventual consistency
3. Message Queues:
SQS for async processing
Decouples producer and consumer
Guaranteed delivery (with DLQ for failures)

Serverless Architecture
Benefits:
No server management
Pay only for execution
Automatic scaling
Challenges:
Cold starts
Limited execution time (15 minutes max)
Vendor lock-in
Testing complexity

Pattern:

API Gateway → Lambda → RDS/DynamoDB



CloudWatch Logs

Optimization:
Provisioned concurrency for critical functions
Layers for shared code and dependencies
Caching at API Gateway level
Native images (GraalVM) for faster cold starts

Event-Driven Architecture
Components:
Event source: API, database stream, queue
Event bus: SNS topic or Kinesis stream
Event consumers: Lambda, SQS, Kinesis subscribers

Pattern:

Order Service publishes "OrderCreated" event



SNS Topic

Subscriptions:
- Notification Service (email confirmation)
- Inventory Service (reduce stock)
- Analytics Service (track metrics)
- Payment Service (process payment)

Benefits:
Decoupled services
Easy to add new consumers
Audit trail of events
Interview Focus:
Design microservices architecture for an e-commerce application
Explain eventual consistency and how to handle it
Discuss trade-offs between synchronous and asynchronous communication
How would you handle distributed transactions?

Interview Questions & Answers


Architecture & Design
Q1: Design a scalable e-commerce platform on AWS
Expected Answer:
Frontend:
- React/Angular app
- S3 + CloudFront for static content
- Custom domain via Route 53

API Layer:
- API Gateway for REST endpoints
- Lambda authorizer for authentication with Cognito
- Rate limiting to prevent abuse

Microservices:
- ECS Fargate or EKS for containerized services
- Auto-scaling based on load
- Services: Product, Order, Payment, Notification, Inventory
- Shared PostgreSQL RDS for transactional data
- DynamoDB for session/cache data
- ElastiCache for hot data

Data:
- RDS Multi-AZ for durability
- Read replicas for scaling reads
- DynamoDB for high-throughput, low-latency access
- S3 for product images, customer documents
- RDS backups for disaster recovery

Communication:
- Synchronous: REST between services via ALB
- Asynchronous: SNS/SQS for order processing
- CloudWatch for centralized logging

Security:
- VPC with public/private subnets
- Security groups restrict traffic
- IAM roles for service-to-service communication
- Secrets Manager for database credentials
- Cognito for user authentication
- HTTPS/TLS throughout

CI/CD:
- GitHub for source control
- CodePipeline/GitHub Actions for CI/CD
- CodeBuild for building containers
- Deploy to ECS/EKS with rolling updates

Monitoring:
- CloudWatch alarms for key metrics
- X-Ray for distributed tracing
- CloudWatch Insights for log analysis

Q2: Your Java application has slow database queries. How would you diagnose and fix?
Expected Answer:
Diagnosis:
1. Check CloudWatch RDS metrics:
- Database CPU usage
- Read/Write latency
- IOPS utilization
- Database connections count

2. Enable RDS query logging:


- PostgreSQL: log_min_duration_statement
- MySQL: slow_query_log

3. Use RDS Performance Insights:


- Identify hot queries
- See which SQL takes most time

4. In application:
- Add Spring Boot actuator metrics
- Check connection pool statistics
- Monitor query execution time

Solutions:
1. Query Optimization:
- Use EXPLAIN ANALYZE to understand query plan
- Add indexes on frequently queried columns
- Rewrite complex joins
- Use database statistics (ANALYZE command)

2. Application Level:
- Configure HikariCP pool:
- maximumPoolSize: 10-20 (tune based on connections)
- minimumIdle: Match database connections
- maxLifetime: 30 minutes
- Use prepared statements (prevents SQL injection, enables caching)
- Batch updates instead of individual inserts

3. Infrastructure:
- Consider larger RDS instance (more CPU/memory)
- Enable RDS storage autoscaling
- Use read replicas for read-heavy queries
- Consider caching layer (ElastiCache) for hot data

4. Data Level:
- Archive old data to S3 (partition strategy)
- Normalize schema if over-denormalized
- Denormalize if over-normalized (data duplication)
Q3: How would you implement zero-downtime deployment for Java application?
Expected Answer:

For ECS:
1. Update task definition with new image:
- New task definition revision created

2. Update ECS service:


- desiredCount stays same (e.g., 3)
- Minimum healthy percent: 100%
- Maximum percent: 150%
- This allows 1.5x tasks temporarily during update

3. Process:
a. Spin up new tasks with updated image
b. Health checks confirm new tasks are healthy
c. ALB starts routing to new tasks
d. Old tasks drain connections (deregistration delay 30s)
e. Old tasks terminated

4. Configuration:
- Health check: /actuator/health (Spring Boot)
- Deregistration delay: 30-60 seconds
- healthy/unhealthy thresholds: 2 consecutive checks

For EKS:
1. Rolling update strategy:
maxSurge: 1 (allow 1 extra pod temporarily)
maxUnavailable: 0 (no pods go down)

2. Pod lifecycle:
- preStop hook to gracefully shutdown
- terminationGracePeriodSeconds: 30 (wait for connections to drain)
- readinessProbe: Remove from service before killing

3. Blue-Green deployment:
- Deploy new version to green environment
- Test completely
- Switch traffic from blue to green
- Keep blue as rollback option

For Lambda:
- Gradual traffic shifting: Linear, Canary, All at once
- SAM/CloudFormation Hooks for automated rollback
- Test in staging first
Q4: How would you handle database connection pool exhaustion?
Expected Answer:
Symptoms:
- "Cannot acquire a connection, pool error Timeout waiting for idle object"
- Application becomes unresponsive
- Database shows high connection count

Root causes:
1. Too many concurrent requests
2. Connections not being returned (connection leak)
3. Slow queries holding connections longer than needed
4. Connection pool too small for workload

Investigation:
1. Check HikariCP metrics:
- [Link] (current)
- [Link] (waiting)
- [Link] (timeouts)

2. Check database:
- SELECT COUNT(*) FROM information_schema.processlist
- SHOW FULL PROCESSLIST (MySQL)
- SELECT * FROM pg_stat_activity (PostgreSQL)

3. Check logs:
- Look for "Timeout waiting" errors
- Identify which queries are slow

Solutions:
1. Increase pool size:
- HikariCP: maximumPoolSize (tune upward)
- Start with: 10 + (2 × number of CPU cores)
- Monitor and adjust based on load

2. Reduce connection usage:


- Optimize slow queries (see Q2)
- Use fetchSize for large result sets
- Close connections explicitly in finally blocks

3. Find connection leaks:


- Code review: Ensure try-with-resources
- Use HikariCP leak detection:
leakDetectionThreshold: 60000 (60 seconds)
- Check logs for "Connection is not closed" warnings

4. Connection validation:
- connectionTestQuery: SELECT 1
- idleTimeout: 10 minutes
- maxLifetime: 30 minutes

5. Infrastructure:
- RDS: Increase max connections parameter
- Add read replicas to distribute reads

Q5: How would you implement authentication and authorization for microservices?
Expected Answer:
Authentication (who are you):
1. User signs into Cognito User Pool:
- Username/password
- Multi-factor authentication option

2. Cognito returns tokens:


- ID token: User identity (claims: sub, name, email, groups)
- Access token: For calling APIs
- Refresh token: For getting new tokens when expired

3. Frontend stores tokens (secure HttpOnly cookie preferred)

Authorization (what can you do):


1. API Gateway Lambda Authorizer:
- Receives request with token
- Validates token signature using Cognito public keys
- Extracts claims (user ID, groups)
- Returns policy:
{
"principalId": "user-id",
"policyDocument": {
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": "arn:aws:execute-api:region:account:apiid/*"
}
]
}
}
- Caches result for 5 minutes

2. Application level (Spring Security):


- JWT token validation:
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
[Link]()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/api/**").authenticated()
.and()
.oauth2ResourceServer()
.jwt();
return [Link]();
}
}

3. Access control patterns:


- Role-based: ADMIN, USER, GUEST
- Attribute-based: department, team, region
- Custom claims in JWT: groups, permissions

4. Service-to-service:
- Assume IAM role for internal service calls
- Use SigV4 signing for AWS service calls
- Use mTLS certificates for Kubernetes
- API keys for external service calls

5. Secrets management:
- Never hardcode credentials
- Use IAM roles for EC2/ECS/Lambda
- Secrets Manager for passwords/keys
- Rotate regularly

Best practices:
- Short-lived tokens (15 minutes for access token)
- Refresh tokens longer-lived (7 days)
- Always use HTTPS
- Validate tokens on every request
- Use security headers (CORS, CSP, X-Frame-Options)

Operational Questions
Q6: Your Lambda function has high cold start latency. How would you optimize?
Expected Answer:
Diagnosis:
- CloudWatch metric: Lambda Duration
- Look for spikes when no invocations for a while
- Java cold starts typically 1-2 seconds

Optimization strategies:

1. Language/Framework:
- Use Quarkus or Micronaut (optimized for Lambda)
- GraalVM native image: 50-200ms cold start
- Reduces JAR size and startup time

2. Code optimization:
- Initialize heavy objects outside handler
- Use connection pooling
- Lazy load dependencies
- Remove unused libraries

3. Memory allocation:
- Increase memory: 1GB has 3x CPU vs 128MB
- More CPU → faster cold start
- More memory → higher cost
- Sweet spot: usually 512MB-1GB for Java

4. Provisioned concurrency:
- Keep specified number of containers warm
- Costs even when not invoked
- Use for critical functions
- Example: API with consistent traffic

5. Container image optimization:


- Use native images (~200MB vs ~500MB)
- Remove unnecessary layers
- Use multi-stage Docker builds
- Strip debug symbols

6. AWS optimizations:
- EphemeralStorage: Increase to 10GB (faster disk)
- Function improvements: Use Lambda@Edge for CloudFront
- Architecture: Use Graviton processors for better perf

7. Design patterns:
- Use SQS for async processing (cold start less critical)
- Use API Gateway caching for repeated requests
- Lambda Reserved Concurrency for baseline performance
Configuration example:
- Memory: 1024 MB
- Architecture: arm64 (Graviton)
- Timeout: 60 seconds
- Ephemeral storage: 10GB
- Provisioned concurrency: 100

Q7: How would you debug a production issue with minimal log visibility?
Expected Answer:

Immediate actions:
1. Check recent changes:
- What code was deployed?
- Any infrastructure changes?
- Configuration updates?

2. Check dashboards:
- CloudWatch metrics (errors, latency, CPU)
- Application metrics (custom)
- Database performance
- Network throughput

3. Check logs:
- CloudWatch Logs groups
- Filter for ERROR level
- Look at timestamps around issue start
- Use CloudWatch Insights to correlate metrics

Query examples:

fields @timestamp, @message, @logStream | filter @message like /ERROR/ | stats count()
by @logStream
4. Distributed tracing:
- X-Ray service map
- Identify which service is slow/failing
- Trace specific requests

5. Check alarms:
- Which alarms fired?
- What thresholds were exceeded?

Systematic investigation:
1. Is it infrastructure or application?
- Check resource utilization (CPU, memory, disk)
- RDS: database connections, CPU, IOPS

2. Is it code or configuration?
- Compare current vs previous deployment
- Check environment variables
- Check database credentials working

3. Is it external dependencies?
- Can you reach RDS?
- Can you reach external APIs?
- DNS resolution working?

Tactical additions (if low visibility):


```java
// Add temporary debug logging
[Link]("Entering processOrder with orderId={}", orderId);
[Link]("Database query returned {} results", [Link]());
[Link]("External API call took {}ms", duration);

// Add custom metrics


[Link](new MetricDatum()
.withMetricName("[Link]")
.withValue(1.0));

// Add distributed tracing


[Link]("processOrder");
try {
// code
} finally {
[Link]();
}
```
Preventive measures:
- Structured logging (JSON) for easier parsing
- Appropriate log levels (INFO for business events, DEBUG for detailed flow)
- Feature flags to toggle new code
- Canary deployments to catch issues early
- Good monitoring/alerts before going critical

Q8: How would you perform a database migration with zero downtime?
Expected Answer:
Scenario: Migrate from MySQL to PostgreSQL

Phase 1: Preparation (offline)


1. Create target PostgreSQL RDS instance
- Multi-AZ enabled
- Same security groups as application
- Backup enabled
- Parameter group tuned

2. Test migration:
- Use AWS DMS (Database Migration Service)
- Perform full load test
- Verify data integrity
- Test application against target

Phase 2: Enable dual-write (online, low risk)


1. Update application:
- Write to both MySQL and PostgreSQL
- Read from MySQL (primary)
- Validate PostgreSQL writes succeed
- Monitor for issues

2. Duration: 24-48 hours


- Allows catching edge cases
- Rollback simple (just revert code)

Phase 3: Switch reads to PostgreSQL (online)


1. Update application:
- Read from PostgreSQL (primary)
- Write still goes to both
- Monitor error rates

2. Rollback procedure:
- Switch reads back to MySQL
- Change takes effect immediately

Phase 4: Cleanup (online)


1. Remove MySQL writes from code
2. Keep MySQL as backup for period
3. Eventually decommission MySQL

Using AWS DMS:


- Create replication instance
- Create source (MySQL) and target (PostgreSQL) endpoints
- Create migration task:
- Full load + ongoing replication
- Transformation rules (data type conversion)
- Validation checks enabled

DMS handles:
- Schema conversion
- Full load of existing data
- CDC (Change Data Capture) for ongoing updates
- Validation of data consistency

Rollback strategy:
- Keep MySQL running and updated
- If issues in PostgreSQL, switch back
- PostgreSQL can temporarily write to MySQL for validation

Performance Questions
Q9: How would you optimize cost for a Java application on AWS?
Expected Answer:
Compute:
- Use Fargate Spot (70% discount) for non-critical workloads
- Reserved instances for baseline load
- Scale down during off-hours
- Right-size instances (monitor utilization)

Database:
- Use RDS Multi-AZ only if needed (doubles cost)
- Read replicas only for actual read scaling
- Use DynamoDB on-demand for variable workloads
- DynamoDB provisioned for predictable loads
- Archive old data to S3 (not in database)

Storage:
- S3 Intelligent-Tiering for automatic archiving
- Use appropriate storage class (Standard, IA, Glacier)
- Delete unused snapshots
- Use S3 lifecycle policies

Network:
- CloudFront for CDN (reduces origin calls)
- NAT gateway charges: Consider NAT instances for lower volume
- VPC endpoints for private AWS service access
- Data transfer: Keep traffic within AWS region

Lambda:
- Right-size memory allocation
- Use on-demand pricing for variable workloads
- Reserved concurrency for baseline
- Avoid unnecessary cold starts

Monitoring:
- Use AWS Cost Explorer to identify expensive services
- Set up cost anomaly alerts
- Use tagging for cost allocation
- Reserved capacity discounts

Example costs comparison:


Scenario: Process 100M events/month

Option 1 (Expensive):
- Lambda 1GB: $50k/month
- RDS Multi-AZ: $2k/month
- Total: $52k/month

Option 2 (Optimized):
- SQS for queueing: $1k/month
- Lambda 512MB + Spot: $15k/month
- RDS Single-AZ with read replica: $1.2k/month
- DynamoDB on-demand: $3k/month
- Total: $20k/month (60% savings)

Summary: Common Interview Mistakes to Avoid


1. Not considering trade-offs
Every technology has pros/cons
Discuss when to use what
2. Overcomplicating architecture
Start simple, add complexity if needed
Don't use Kubernetes for simple apps
3. Ignoring security
Always mention security group configuration
Never hardcode credentials
Use IAM roles
4. Not thinking about operations
How will you monitor it?
How will you debug issues?
How will you scale?
5. Missing cost considerations
Multi-AZ is expensive
Always think about cost optimization
6. Forgetting about disasters
What's your recovery strategy?
How often do you backup?
Can you restore quickly?

Practice Scenarios
Scenario 1: A microservice has 1% of requests timing out. Walk through your
troubleshooting.
Scenario 2: You need to deploy a new service to production with confidence. Design the
rollout strategy.
Scenario 3: Your database is running out of space. How do you handle this without
downtime?
Scenario 4: An application has inconsistent performance. Sometimes fast, sometimes slow.
Diagnose the issue.
Scenario 5: You need to reduce costs by 40% without reducing capacity. What changes
would you make?

This guide covers the full scope of your experience. Practice explaining each concept in
your own words, and be prepared to discuss trade-offs and real-world experiences you've
had. Good luck with your interview!

You might also like