---
title: "AWS Certified Developer Associate Flashcards (DVA-C02)"
description: "Full exam coverage for the AWS Certified Developer – Associate (DVA-C02) exam using spaced repetition. Covers Development, Security, Deployment, Troubleshooting, and AWS SDK/CLI/APIs."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/flashcards/post/aws-certified-developer-associate-flashcards
---

# AWS Certified Developer Associate Flashcards (DVA-C02)

## Flashcards

### 1. What is AWS Lambda and how is it invoked?

AWS Lambda runs code in response to events without managing servers. It can be invoked synchronously (API Gateway, SDK), asynchronously (S3, SNS, EventBridge), or via event source mappings (SQS, Kinesis, DynamoDB Streams). Each invocation runs in an isolated execution environment.

```
# Synchronous invoke via CLI
aws lambda invoke \
  --function-name myFunction \
  --payload '{"key":"value"}' \
  response.json

```

### 2. What is a Lambda execution environment and cold start?

A Lambda execution environment is an isolated runtime container. A cold start occurs when Lambda must initialize a new environment (download code, start runtime, run init code) before handling a request. Subsequent invocations reuse the warm environment. Cold starts add latency minimize with Provisioned Concurrency or keeping functions warm.

### 3. What is Lambda Provisioned Concurrency?

Provisioned Concurrency pre-initializes a specified number of Lambda execution environments so they are always ready to respond instantly. It eliminates cold starts for latency-sensitive applications and is billed separately from on-demand invocations.

### 4. What are Lambda environment variables?

Lambda environment variables are key-value pairs injected into the function's runtime environment. They externalize configuration (DB endpoints, feature flags) from code. They can be encrypted with AWS KMS for sensitive values.

```
import os
DB_HOST = os.environ['DB_HOST']
API_KEY = os.environ['API_KEY']

```

### 5. What is the Lambda handler and its event/context parameters?

The handler is the entry point function Lambda calls. It receives an event object (the trigger payload) and a context object (runtime info function name, memory limit, remaining time, request ID).

```
def handler(event, context):
    print(context.function_name)
    print(context.get_remaining_time_in_millis())
    return {"statusCode": 200, "body": "OK"}

```

### 6. What are Lambda layers?

Lambda layers are ZIP archives containing libraries, custom runtimes, or other dependencies that can be shared across multiple functions. They reduce deployment package size and enable reuse of common code without bundling it into every function.

### 7. What is Lambda Destinations?

Lambda Destinations route the result of an asynchronous invocation to a target (SQS, SNS, EventBridge, or another Lambda) on success or failure. They replace the need for DLQs for async flows and provide richer event context.

### 8. What is Amazon API Gateway and its integration types?

API Gateway manages REST, HTTP, and WebSocket APIs. Integration types: Lambda Proxy passes the full request to Lambda; Lambda controls the response. Lambda Non-Proxy API Gateway transforms request/response via mapping templates. HTTP proxies to an HTTP backend. AWS Service directly integrates with AWS services (e.g., SQS, DynamoDB). Mock returns a response without calling a backend.


### 9. What is API Gateway request/response mapping?

Mapping templates (written in Velocity Template Language VTL) transform the request before sending it to the integration and transform the response before returning it to the client. Used in non-proxy Lambda integrations to reshape payloads.

### 10. What is API Gateway usage plans and API keys?

Usage plans define throttling (requests per second) and quota (requests per day/month) limits for API consumers. API keys are identifiers associated with usage plans to track and control per-client access.

### 11. What is API Gateway stage variables?

Stage variables are key-value pairs associated with an API Gateway deployment stage (dev, staging, prod). They allow a single API definition to point to different Lambda aliases, HTTP endpoints, or config values per stage.

```
# Lambda ARN using stage variable
arn:aws:lambda:us-east-1:123:function:myFunc:${stageVariables.lambdaAlias}

```

### 12. What is Amazon DynamoDB and its data model?

DynamoDB is a serverless NoSQL key-value and document database. Every item must have a primary key either a simple partition key (PK) or a composite key (PK + sort key). Items within a table can have different attributes. There are no joins or complex queries without indexes.

### 13. What is a DynamoDB partition key vs composite key?

A partition key (hash key) alone uniquely identifies an item. A composite key combines a partition key and sort key multiple items can share the same partition key but must have unique sort keys. Sort keys enable range queries within a partition.

### 14. What is a DynamoDB Local Secondary Index (LSI)?

An LSI uses the same partition key as the base table but a different sort key. It must be created at table creation time, shares the table's read/write capacity, and enables alternate sort-order queries within a partition. Limited to 5 per table.

### 15. What is a DynamoDB Global Secondary Index (GSI)?

A GSI has a completely different partition key and optional sort key from the base table. It can be created or deleted at any time, has its own provisioned throughput, and enables querying on any attribute. Limited to 20 per table.

### 16. What is DynamoDB read consistency?

Eventually Consistent Reads (default) may return stale data, uses 0.5 RCU per 4KB. Strongly Consistent Reads always returns the latest data, uses 1 RCU per 4KB, not supported on GSIs. Transactional Reads uses 2 RCUs per 4KB, guarantees ACID across multiple items.


### 17. What are DynamoDB Read Capacity Units (RCU) and Write Capacity Units (WCU)?

1 RCU = 1 strongly consistent read OR 2 eventually consistent reads of up to 4KB/s. 1 WCU = 1 write of up to 1KB/s. Transactional reads/writes consume 2x RCU/WCU. Items larger than 4KB (reads) or 1KB (writes) require multiple units.


### 18. What is DynamoDB on-demand vs provisioned capacity?

Provisioned capacity requires you to specify RCUs and WCUs in advance use Auto Scaling or manual adjustments. On-demand capacity automatically scales to any traffic level with no capacity planning, billed per request. On-demand is more expensive per request but simpler for unpredictable workloads.

### 19. What is the DynamoDB Streams?

DynamoDB Streams captures a time-ordered sequence of item-level changes (INSERT, MODIFY, REMOVE) in a table. Stream records are available for 24 hours and can trigger Lambda for real-time processing, replication, or audit logging.

### 20. What is DynamoDB Transactions?

DynamoDB Transactions provide ACID guarantees across multiple items and tables in a single account and region. TransactWriteItems and TransactGetItems operations either all succeed or all fail, consuming 2x the normal RCU/WCU.

### 21. What is the DynamoDB scan vs query operation?

Query retrieves items with a specific partition key and optional sort key condition efficient and uses only the capacity for matched items. Scan reads every item in the table expensive and slow for large tables. Always prefer Query over Scan.

### 22. What is Amazon SQS and its key properties?

SQS is a managed message queue for decoupling services. Key properties message retention (1 min to 14 days, default 4 days), message size up to 256KB, visibility timeout (prevents duplicate processing), long polling (up to 20s), and dead-letter queues for failed messages.

### 23. What is the difference between SQS Standard and FIFO queues?

Standard queues offer unlimited throughput, at-least-once delivery, and best-effort ordering duplicates possible. FIFO queues guarantee exactly-once processing, strict ordering within a message group, and up to 3,000 messages/second with batching.

### 24. What is SQS message visibility timeout?

After a consumer reads a message, it becomes invisible for the visibility timeout period. If the consumer successfully processes and deletes it within that time, it is gone. If not, the message reappears for reprocessing. Set it longer than your processing time to avoid duplicates.

### 25. What is Amazon SNS and fan-out pattern?

SNS is a pub/sub messaging service. A publisher sends to a topic; SNS pushes to all subscribers (Lambda, SQS, HTTP, email, SMS). The fan-out pattern combines SNS with multiple SQS queues SNS delivers one message to many queues for parallel, independent processing.

### 26. What is Amazon EventBridge?

EventBridge is a serverless event bus routing events from AWS services, SaaS apps, and custom sources to targets like Lambda, SQS, Step Functions, and API Gateway. Rules match events using JSON pattern matching and route to one or more targets.

### 27. What is Amazon Kinesis Data Streams for developers?

Kinesis Data Streams ingests and processes real-time data. Data is split across shards (1MB/s in, 2MB/s out each). Consumers use the Kinesis Client Library (KCL) or Lambda. Records are retained up to 365 days. Use shard splitting to scale throughput.

### 28. What is Amazon S3 event notification?

S3 can publish events (object created, deleted, restored) to Lambda, SQS, or SNS. Event notifications trigger serverless workflows automatically e.g., generating thumbnails on upload, processing CSV files, or sending alerts on deletion.

### 29. What is S3 presigned URLs?

A presigned URL grants temporary access to a private S3 object without requiring the requester to have AWS credentials. Generated by an IAM principal with S3 permissions, the URL embeds credentials and expires after a set duration.

```
import boto3
s3 = boto3.client('s3')
url = s3.generate_presigned_url(
    'get_object',
    Params={'Bucket': 'mybucket', 'Key': 'file.txt'},
    ExpiresIn=3600
)

```

### 30. What is Amazon ElastiCache for developers?

ElastiCache (Redis or Memcached) is used in applications to cache database query results, session data, or computed values. Common patterns lazy loading (cache on miss), write-through (update cache on write), and session store (stateless apps behind a load balancer).

### 31. What is the lazy loading caching pattern?

Lazy loading only writes data to the cache when it is requested and not found (cache miss). The application first checks the cache, on miss fetches from DB and writes to cache. Pros only caches what is needed. Cons initial request is slower, stale data possible.

### 32. What is the write-through caching pattern?

Write-through updates the cache every time data is written to the database. The cache is always up to date. Pros no stale data. Cons cache may contain data that is never read (wasted memory), and write latency is higher.

### 33. What is IAM policy evaluation for developers?

AWS evaluates all policies attached to the identity: 1. Explicit Deny always wins. 2. Explicit Allow grants access if no deny. 3. Default Deny everything is denied unless explicitly allowed. Resource-based policies and identity policies are evaluated together for same-account access.


### 34. What are IAM roles for EC2 and Lambda?

Attaching an IAM role to EC2 or Lambda grants the service temporary credentials via the instance metadata service (IMDS) or Lambda execution role. This is the correct way to give AWS services permissions never hardcode access keys.

```
# boto3 automatically uses the Lambda execution role
import boto3
s3 = boto3.client('s3')
s3.list_buckets()

```

### 35. What is AWS STS AssumeRole?

AssumeRole returns temporary security credentials for an IAM role. Used for cross-account access, federated identities, and granting temporary elevated permissions. The credentials include an access key, secret key, and session token valid for 15 minutes to 12 hours.

```
sts = boto3.client('sts')
response = sts.assume_role(
    RoleArn='arn:aws:iam::123456789:role/MyRole',
    RoleSessionName='MySession'
)
creds = response['Credentials']

```

### 36. What is AWS Cognito User Pools vs Identity Pools?

User Pools are user directories for authentication sign-up, sign-in, MFA, JWT tokens. Identity Pools (Federated Identities) exchange a Cognito, social, or SAML token for temporary AWS credentials via STS, allowing direct AWS service access from client apps.

### 37. What is a Cognito JWT token and its types?

After authentication, Cognito User Pools return three JWT tokens ID token (user identity claims, used to authenticate to backend), Access token (authorizes API calls, used with API Gateway), and Refresh token (used to obtain new ID/Access tokens without re-authentication).

### 38. What is AWS KMS for developers?

KMS manages encryption keys. Developers use GenerateDataKey to get a plaintext + encrypted data key for envelope encryption, Encrypt/Decrypt for small data (<4KB), and GenerateDataKeyWithoutPlaintext for deferred decryption. All KMS calls are logged in CloudTrail.

```
kms = boto3.client('kms')
response = kms.generate_data_key(
    KeyId='alias/mykey',
    KeySpec='AES_256'
)
plaintext_key = response['Plaintext']
encrypted_key = response['CiphertextBlob']

```

### 39. What is envelope encryption?

Envelope encryption encrypts data with a data key (DEK), then encrypts the DEK with a master key (CMK) in KMS. Only the encrypted DEK is stored alongside the data. This avoids sending large data to KMS and reduces KMS API calls.

### 40. What is AWS Secrets Manager for developers?

Secrets Manager stores and automatically rotates secrets (DB passwords, API keys). Applications retrieve secrets at runtime via the API instead of hardcoding them. It integrates natively with RDS for automatic credential rotation.

```
client = boto3.client('secretsmanager')
secret = client.get_secret_value(SecretId='prod/db/password')
password = secret['SecretString']

```

### 41. What is SSM Parameter Store for developers?

SSM Parameter Store stores configuration data and secrets as parameters. String, StringList, and SecureString (KMS-encrypted) types. SecureString parameters can be fetched and decrypted in a single API call. Cheaper than Secrets Manager for non-rotating config.

```
ssm = boto3.client('ssm')
param = ssm.get_parameter(
    Name='/myapp/db/password',
    WithDecryption=True
)
value = param['Parameter']['Value']

```

### 42. What is S3 server-side encryption for developers?

SSE-S3 AWS manages AES-256 keys, enabled by default, no extra cost. SSE-KMS keys in KMS, audit trail, key rotation, requires kms:GenerateDataKey permission. SSE-C customer provides keys per request, HTTPS required, AWS does not store the key. Client-side encryption encrypt before upload, AWS never sees plaintext.


### 43. What is CORS and how is it configured in API Gateway and S3?

CORS (Cross-Origin Resource Sharing) allows web browsers to make requests to a different domain. Enable CORS on API Gateway to allow browser-based clients from other origins. On S3, add a CORS configuration JSON to the bucket for browser-based uploads/downloads.

```
# S3 CORS config
[{"AllowedOrigins": ["https://myapp.com"],
  "AllowedMethods": ["GET","PUT"],
  "AllowedHeaders": ["*"]}]

```

### 44. What is API Gateway Lambda authorizer?

A Lambda authorizer (formerly custom authorizer) is a Lambda function that validates a bearer token (JWT, OAuth) or request parameters before API Gateway allows the request. It returns an IAM policy document allowing or denying access to the API resource.

### 45. What is API Gateway Cognito authorizer?

A Cognito authorizer validates a Cognito User Pool JWT token attached to the request's Authorization header. API Gateway verifies the token's signature and expiry automatically without writing a Lambda authorizer function.

### 46. What is AWS Elastic Beanstalk?

Elastic Beanstalk is a PaaS for deploying web applications. You upload your code; Beanstalk handles provisioning EC2, load balancers, Auto Scaling, and monitoring. It supports Node.js, Python, Java, .NET, PHP, Ruby, Go, and Docker. You retain full control of underlying resources.

### 47. What are Elastic Beanstalk deployment policies?

All at once deploy to all instances simultaneously. Fastest but causes downtime. Rolling deploy in batches. Reduced capacity during deployment, no downtime. Rolling with additional batch launches extra instances first. Full capacity maintained. Immutable deploys to brand new instances. Safest, zero downtime, easy rollback. Blue/Green swap environment URLs after testing. Instant rollback, requires DNS change.


### 48. What is an Elastic Beanstalk .ebextensions?

.ebextensions is a folder in your application bundle containing YAML/JSON config files (.config) that customize and configure the Beanstalk environment install packages, run commands, set environment variables, configure files, and modify CloudFormation resources.

```
# .ebextensions/packages.config
packages:
  yum:
    git: []
    htop: []

```

### 49. What is AWS CodeDeploy and its deployment types?

CodeDeploy automates application deployments to EC2, on-premises, Lambda, and ECS. In-place stops, updates, restarts on existing instances (EC2/on-prem only). Blue/Green shifts traffic to new instances/Lambda versions/ECS tasks after validation. Use AppSpec.yml to define lifecycle hooks and deployment steps.


### 50. What is the CodeDeploy AppSpec file?

AppSpec.yml (or appspec.json) defines the deployment actions for CodeDeploy. For EC2 it specifies files to copy and lifecycle event hooks (BeforeInstall, AfterInstall, ApplicationStart, ValidateService). For Lambda it specifies the function name, alias, and traffic shifting hooks.

```
version: 0.0
os: linux
files:
  - source: /
    destination: /var/www/html
hooks:
  AfterInstall:
    - location: scripts/install_deps.sh
  ApplicationStart:
    - location: scripts/start_server.sh

```

### 51. What is AWS CodePipeline?

CodePipeline is a fully managed CI/CD service that orchestrates build, test, and deploy stages. It integrates with CodeCommit, CodeBuild, CodeDeploy, CloudFormation, Elastic Beanstalk, and third-party tools like GitHub and Jenkins. Each stage passes artifacts via S3.

### 52. What is AWS CodeBuild?

CodeBuild is a managed build service that compiles source code, runs tests, and produces deployment artifacts. It uses a buildspec.yml file to define build phases. You pay per build minute no idle server costs.

```
# buildspec.yml
version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 18
  build:
    commands:
      - npm install
      - npm test
      - npm run build
artifacts:
  files:
    - '**/*'
  base-directory: dist

```

### 53. What is AWS SAM (Serverless Application Model)?

AWS SAM is an open-source framework for building serverless applications. It extends CloudFormation with simplified syntax for Lambda functions, API Gateway APIs, DynamoDB tables, and event sources. The SAM CLI enables local testing and deployment.

```
# template.yaml
Transform: AWS::Serverless-2016-10-31
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.11
      Events:
        Api:
          Type: Api
          Properties:
            Path: /hello
            Method: get

```

### 54. What is the SAM CLI and its key commands?

sam init       scaffold a new SAM project sam build      build the application sam local invoke invoke a Lambda function locally sam local start-api start a local API Gateway sam deploy     package and deploy to AWS (uses CloudFormation) sam logs       fetch Lambda logs from CloudWatch


### 55. What is AWS CloudFormation for developers?

CloudFormation provisions AWS infrastructure as code using JSON or YAML templates. Key sections Parameters (inputs), Resources (required, defines AWS resources), Outputs (exported values), Mappings (static lookup tables), Conditions (conditional resource creation).

### 56. What is a CloudFormation stack and change set?

A stack is a collection of AWS resources managed as a single unit via a CloudFormation template. A change set previews the changes CloudFormation will make to a stack before execution showing additions, modifications, and deletions without applying them.

### 57. What is CloudFormation cross-stack references?

Cross-stack references allow one stack to export values (using Outputs with Export) and another stack to import them (using Fn::ImportValue). This enables modular stacks where, for example, a network stack exports VPC and subnet IDs for application stacks to use.

```
# Stack A export
Outputs:
  VpcId:
    Value: !Ref MyVPC
    Export:
      Name: MyVPC-ID

# Stack B import
Resources:
  MyInstance:
    Properties:
      VpcId: !ImportValue MyVPC-ID

```

### 58. What is Lambda traffic shifting with aliases?

Lambda aliases point to specific function versions. Using CodeDeploy or SAM, you can configure weighted routing on an alias to shift traffic gradually between two versions (e.g., 90% v1, 10% v2), enabling canary or linear deployments with automatic rollback on CloudWatch alarms.

```
# SAM canary deployment
AutoPublishAlias: live
DeploymentPreference:
  Type: Canary10Percent10Minutes

```

### 59. What is Amazon ECR?

Amazon ECR is a managed Docker container image registry. Images are stored in private or public repositories, scanned for vulnerabilities, and replicated across regions. It integrates with ECS, EKS, Lambda (container images), and CodeBuild for CI/CD pipelines.

### 60. What is AWS X-Ray for developers?

X-Ray traces requests through distributed applications. You instrument code with the X-Ray SDK to create segments and subsegments. The service map visualizes dependencies; traces show latency, errors, and throttling at each step. Enable active tracing on Lambda and API Gateway.

```
# Python instrument boto3 with X-Ray
from aws_xray_sdk.core import xray_recorder, patch_all
patch_all()  # patches boto3, requests, etc.

```

### 61. What are X-Ray segments, subsegments, and annotations?

A segment represents a unit of work (e.g., a Lambda invocation). Subsegments represent downstream calls (DynamoDB, HTTP). Annotations are indexed key-value pairs you add for filtering traces in the X-Ray console. Metadata is non-indexed additional data on segments.

### 62. What is Amazon CloudWatch for developers?

CloudWatch collects metrics, logs, and events. For developers use PutMetricData to publish custom metrics, CloudWatch Logs for Lambda/application logs, CloudWatch Alarms to trigger SNS/Auto Scaling, and CloudWatch Insights to query logs with a SQL-like syntax.

### 63. What are CloudWatch Lambda metrics to monitor?

Invocations total number of function calls. Errors invocations that resulted in an error. Duration execution time per invocation. Throttles invocations rejected due to concurrency limits. ConcurrentExecutions simultaneous function executions. IteratorAge lag for stream-based triggers (Kinesis, DynamoDB Streams).


### 64. What is Lambda concurrency and throttling?

Lambda concurrency is the number of simultaneous executions. The default account limit is 1,000 concurrent executions per region. Reserved concurrency caps a function's max concurrent executions. When the limit is hit, Lambda throttles synchronous calls return 429, async calls retry.

### 65. What is Lambda reserved vs provisioned concurrency?

Reserved concurrency sets a hard maximum for a function guarantees it is never throttled by other functions but limits its own scale. Provisioned concurrency pre-warms environments to eliminate cold starts. They serve different purposes reserved for isolation, provisioned for latency.

### 66. What causes a Lambda timeout error and how do you fix it?

Lambda times out if the function runs longer than its configured timeout (max 15 minutes). Causes slow DB queries, large payloads, infinite loops, waiting on external APIs. Fix by increasing timeout, optimizing code, using connection pooling (RDS Proxy), or using async patterns.

### 67. What is DynamoDB ProvisionedThroughputExceededException?

This error occurs when your application exceeds the provisioned RCUs or WCUs on a table or GSI. Fix by enabling DynamoDB Auto Scaling, switching to on-demand mode, implementing exponential backoff and retry, using DAX for read caching, or distributing writes across partition keys.

### 68. What is exponential backoff with jitter?

Exponential backoff retries a failed request after an increasing delay (1s, 2s, 4s, 8s…). Adding random jitter spreads retries from multiple clients, preventing thundering herd. The AWS SDK implements exponential backoff automatically for retryable errors.

```
import time, random
for attempt in range(5):
    try:
        response = call_aws_api()
        break
    except ThrottlingException:
        time.sleep((2 ** attempt) + random.random())

```

### 69. What is SQS message processing troubleshooting?

Common issues messages reappearing (visibility timeout too short increase it or call ChangeMessageVisibility), duplicate processing (use FIFO queues or idempotent consumers), messages in DLQ (inspect for processing errors check consumer logs and message format).

### 70. What is API Gateway 502, 403, 429 error troubleshooting?

502 Bad Gateway Lambda returned an invalid response (check response format must include statusCode). 403 Forbidden missing or invalid API key, failed authorizer, or resource policy denial. 429 Too Many Requests throttling due to usage plan limits or Lambda concurrency exhaustion. 504 Gateway Timeout Lambda execution exceeded 29-second API Gateway timeout.


### 71. What is CloudWatch Logs Insights?

Logs Insights lets you interactively query and analyze CloudWatch log data using a purpose-built query language. Useful for finding errors, computing statistics, and building dashboards from Lambda, API Gateway, and application logs.

```
# Find Lambda errors in the last hour
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 50

```

### 72. What is AWS CodeGuru?

AWS CodeGuru has two components CodeGuru Reviewer uses ML to analyze pull requests and flag code defects, security vulnerabilities, and deviations from best practices. CodeGuru Profiler identifies the most expensive lines of code at runtime to optimize performance and reduce cost.

### 73. What is the AWS CLI and how do you configure it?

The AWS CLI is a command-line tool for interacting with AWS services. Configure it with aws configure it prompts for Access Key ID, Secret Access Key, default region, and output format. Credentials are stored in ~/.aws/credentials, config in ~/.aws/config.

```
$ aws configure
AWS Access Key ID: AKIA...
AWS Secret Access Key: ****
Default region name: us-east-1
Default output format: json

```

### 74. What are AWS CLI named profiles?

Named profiles allow multiple sets of credentials and settings in the CLI. Create them with aws configure --profile <name> and use them with --profile flag or the AWS_PROFILE environment variable.

```
$ aws configure --profile dev
$ aws s3 ls --profile dev
$ export AWS_PROFILE=dev

```

### 75. What are AWS CLI output formats?

The CLI supports json (default), yaml, text (tab-separated, good for scripting), and table (human-readable ASCII table). Set with --output flag or in config. Use --query with JMESPath expressions to filter output.

```
$ aws ec2 describe-instances \
    --query 'Reservations[*].Instances[*].InstanceId' \
    --output text

```

### 76. What are AWS SDK clients and their credential resolution order?

AWS SDKs resolve credentials in this order: 1. Explicit credentials in code (avoid in production). 2. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). 3. AWS credentials file (~/.aws/credentials). 4. IAM role for ECS tasks / EC2 instance profile / Lambda execution role. 5. IAM Identity Center (SSO). Never hardcode credentials use IAM roles or environment variables.


### 77. What are AWS SDK retries and how do you configure them?

AWS SDKs automatically retry retryable errors (throttling, 5xx) using exponential backoff. You can configure the retry mode (legacy, standard, adaptive) and max attempts. Standard mode is recommended it adds retry quota to prevent overwhelming a degraded service.

```
import boto3
from botocore.config import Config

config = Config(
    retries={'max_attempts': 10, 'mode': 'standard'}
)
client = boto3.client('dynamodb', config=config)

```

### 78. What is the AWS SDK pagination?

Many AWS APIs return paginated results with a NextToken or Marker. Use paginators in the SDK to automatically iterate through all pages without manually tracking tokens.

```
paginator = boto3.client('s3').get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket='mybucket'):
    for obj in page['Contents']:
        print(obj['Key'])

```

### 79. What is the AWS SDK waiters?

Waiters poll an API operation until a desired state is reached (e.g., instance running, stack create complete). They handle polling intervals and maximum attempts automatically, simplifying automation scripts.

```
ec2 = boto3.client('ec2')
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=['i-1234567890abcdef0'])
print("Instance is running!")

```

### 80. What are AWS service endpoints and regions in the SDK?

Each AWS service has regional endpoints (e.g., s3.us-east-1.amazonaws.com). Specify the region when creating a client. Use endpoint_url to point to custom endpoints (LocalStack for local testing, VPC Interface Endpoints for private access).

```
# LocalStack local testing
s3 = boto3.client(
    's3',
    region_name='us-east-1',
    endpoint_url='http://localhost:4566'
)

```

### 81. What is AWS SDK for JavaScript v3 modular imports?

AWS SDK v3 uses modular packages import only the clients and commands you need, reducing bundle size. Each service is a separate npm package. Commands are separate from clients, enabling tree-shaking.

```
import { DynamoDBClient, GetItemCommand } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({ region: "us-east-1" });
const response = await client.send(
  new GetItemCommand({ TableName: "Users", Key: { id: { S: "123" } } })
);

```

### 82. What is the DynamoDB DocumentClient?

The DynamoDB DocumentClient (SDK v2) or lib-dynamodb (SDK v3) simplifies working with DynamoDB by automatically marshalling JavaScript types to DynamoDB AttributeValue format and unmarshalling responses, eliminating the need to specify {S: "value"} type descriptors.


```
// SDK v3 with lib-dynamodb
import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb";
const docClient = DynamoDBDocumentClient.from(client);
const result = await docClient.send(
  new GetCommand({ TableName: "Users", Key: { id: "123" } })
);

```

### 83. What are AWS API error types developers should handle?

ClientErrors (4xx) caused by invalid input, missing permissions, throttling.
  - ThrottlingException / ProvisionedThroughputExceededException retry with backoff.
  - ValidationException fix request parameters.
  - AccessDeniedException fix IAM permissions.
ServerErrors (5xx) AWS-side issues, always safe to retry. Use SDK error codes, not HTTP status codes, for precise handling.


```
try:
    table.get_item(Key={'id': '123'})
except ClientError as e:
    code = e.response['Error']['Code']
    if code == 'ProvisionedThroughputExceededException':
        time.sleep(2)

```

### 84. What is AWS CLI CloudFormation deploy vs create-stack?

aws cloudformation create-stack creates a new stack and fails if it exists. aws cloudformation deploy (via SAM/CDK pattern) uses create-stack for new stacks and update-stack for existing ones idempotent and safer for CI/CD pipelines. It also handles change sets automatically.

```
$ aws cloudformation deploy \
    --template-file template.yaml \
    --stack-name my-app \
    --capabilities CAPABILITY_IAM \
    --parameter-overrides Env=prod

```

### 85. What is the AWS CDK and how does it differ from CloudFormation?

The AWS CDK (Cloud Development Kit) defines infrastructure using TypeScript, Python, Java, or C#. CDK constructs are reusable, composable components that synthesize into CloudFormation templates. CDK provides higher-level abstractions, loops, conditions, and IDE support CloudFormation is the underlying deployment engine.

```
from aws_cdk import Stack, aws_lambda as _lambda
class MyStack(Stack):
    def __init__(self, scope, id, **kwargs):
        super().__init__(scope, id, **kwargs)
        _lambda.Function(self, "MyFunc",
            runtime=_lambda.Runtime.PYTHON_3_11,
            handler="app.handler",
            code=_lambda.Code.from_asset("lambda"))

```

### 86. What is S3 multipart upload and when should you use it?

Multipart upload splits large objects into parts uploaded in parallel, then assembled by S3. Use it for objects larger than 100MB (required above 5GB). Benefits improved throughput, ability to pause and resume, and retry individual failed parts.

```
# boto3 handles multipart automatically with transfer config
from boto3.s3.transfer import TransferConfig
config = TransferConfig(multipart_threshold=1024*25)
s3.upload_file('largefile.zip', 'mybucket', 'largefile.zip',
               Config=config)

```

### 87. What is DynamoDB conditional writes?

Conditional writes only succeed if a specified condition expression evaluates to true, enabling optimistic locking. Use attribute_exists, attribute_not_exists, and comparison operators to prevent overwrites or enforce business rules.

```
table.put_item(
    Item={'id': '123', 'version': 1, 'name': 'Ali'},
    ConditionExpression='attribute_not_exists(id)'
)
# Fails if item with id=123 already exists

```

### 88. What is DynamoDB TTL (Time to Live)?

TTL automatically deletes items from a DynamoDB table after a specified timestamp, reducing storage costs. Enable TTL on a Number attribute storing a Unix epoch timestamp. Expired items are typically deleted within 48 hours they may still appear in reads until removed.

### 89. What is the difference between Lambda synchronous and asynchronous invocation error handling?

Synchronous invocations (API Gateway, SDK) return errors directly to the caller the caller must handle retries. Asynchronous invocations (S3, SNS, EventBridge) automatically retry twice on failure, then route to a DLQ or Lambda Destination for error handling.

### 90. What is API Gateway caching?

API Gateway can cache endpoint responses for a TTL (default 300s, max 3600s) to reduce backend calls and improve latency. Cache is per stage, configurable per method. Clients can bypass the cache with Cache-Control: max-age=0 header if cache invalidation is enabled.
