
Migrating Microsoft SQL Server on Windows EC2 to Amazon S3 Using AWS Glue and Amazon Athena
Learn how to migrate and archive historical Microsoft SQL Server data from Windows EC2 to Amazon S3 using AWS Glue ETL and Apache Parquet. Explore secure JDBC connectivity, private VPC networking, AWS Glue Data Catalog, Amazon Athena SQL queries, incremental data migration, IAM security, CloudWatch monitoring, Terraform automation, and cost optimization for building a scalable, production-ready AWS data archival solution.
AWS Community Builder | AWS Data Engineering | Windows EC2 | Microsoft SQL Server | AWS Glue | Amazon S3 | Amazon Athena

1. Introduction
Many enterprises run business-critical applications on Windows EC2 instances with Microsoft SQL Server as their primary database.
Over time, transactional databases accumulate millions of historical records, increasing storage requirements, backup durations, maintenance complexity, and operational costs.
Consider a SQL Server database containing ten years of orders, invoices, audit records, and transaction history.
The application may need only the latest two years of records for daily operations, but the organization may need older data for compliance, reporting, or occasional customer searches.
Instead of keeping all historical records in SQL Server, we can move eligible data into Amazon S3 and query it using Amazon Athena.
AWS Glue provides managed data integration and transformation capabilities for this architecture.
The resulting pattern is:
SQL Server on Windows EC2 → AWS Glue → Amazon S3 → AWS Glue Data Catalog → Amazon Athena
This architecture separates transactional workloads from historical analytics.
2. Why Migrate Historical SQL Server Data to S3?
Common challenges with large SQL Server databases include:
- Growing EBS storage requirements
- Increasing SQL Server backup and restore times
- Higher database maintenance overhead
- Expensive historical reporting queries
- Long-term retention requirements
- Increased operational complexity
- Historical data rarely accessed by transactional applications
Amazon S3 offers durable object storage for archived datasets, while Athena provides serverless SQL querying over supported data formats.
AWS Glue helps extract, clean, transform, and catalog the data.
Business benefits
Storage efficiency: Historical datasets can be stored as compressed Parquet files.
Reduced database pressure: Historical analytical queries no longer need to run against the production SQL Server database.
Scalable analytics: Athena can query large datasets directly from S3.
Operational separation: The application database and archive analytics environment can scale independently.
Governance: S3, Glue, IAM, KMS, and Lake Formation can support controlled access to archived data.
3. End-to-End AWS Architecture
Business Application | v Windows EC2 Application | v Microsoft SQL Server Windows EC2 | TCP Port 1433 | v AWS Glue ETL JDBC Connection | v Data Extraction | v Data Cleaning / Mapping | v Apache Parquet Format | v Amazon S3 Data Lake | +--------+--------+ | | v v Raw Data Zone Curated Zone | v AWS Glue Crawler | v Glue Data Catalog | v Amazon Athena | v Historical SQL Queries | v Application / ReportingA production architecture may use an S3 landing zone, curated zone, and separate Athena query-results bucket.
4. AWS Services Used
AWS service | Responsibility |
|---|---|
Amazon EC2 Windows | Hosts Microsoft SQL Server |
Microsoft SQL Server | Source relational database |
AWS Glue | Data extraction and transformation |
AWS Glue JDBC Connection | Connectivity to SQL Server |
Amazon S3 | Historical data storage |
AWS Glue Data Catalog | Table and partition metadata |
AWS Glue Crawler | Schema and partition discovery |
Amazon Athena | SQL-based historical analytics |
AWS IAM | Permissions |
AWS KMS | Encryption |
Amazon CloudWatch | Monitoring |
AWS Secrets Manager | Database credentials |
AWS Systems Manager | Private EC2 administration |
5. Design the Historical Data Retention Policy
Before moving data, determine which records qualify for archival.
Example:
SQL Server Orders Table | vCurrent Date | vRetention Policy | +--> Last 24 Months | | | v | Keep in SQL Server | +--> Older Than 24 Months | v Archive to S3Example SQL query:
SELECT OrderID, CustomerID, OrderDate, TotalAmount, OrderStatusFROM dbo.OrdersWHERE OrderDate < DATEADD(MONTH, -24, GETUTCDATE());For production, use a fixed, recorded cutoff timestamp rather than recalculating the cutoff independently during every extraction step.
Account for foreign keys, related tables, retention requirements, and ongoing updates to historical records.
6. Configure SQL Server on Windows EC2
Example source configuration:
EC2 Operating System: Windows ServerDatabase Engine: Microsoft SQL ServerDatabase: SalesDBTable: dbo.OrdersSQL Server Port: TCP 1433Network: Private SubnetStorage: Encrypted Amazon EBSRecommended steps:
- Verify SQL Server TCP/IP connectivity.
- Configure a fixed SQL Server listening port if appropriate.
- Allow inbound SQL Server traffic only from the AWS Glue job's security group.
- Create a dedicated read-only extraction identity.
- Store credentials securely.
- Enable encrypted SQL connections.
- Test extraction queries before processing large tables.
SQL Server may use a different configured port. Do not assume TCP 1433 without checking the actual instance configuration.
7. AWS Glue Connectivity to SQL Server
AWS Glue can read supported SQL Server databases through JDBC.
Example JDBC URL:
jdbc:sqlserver://10.0.20.15:1433;databaseName=SalesDB;encrypt=true;trustServerCertificate=false;Use a hostname and certificate configuration that supports proper TLS certificate validation.
Network requirements
- The Glue connection must use an appropriate VPC, subnet, and security group.
- The SQL Server security group must allow the Glue job's source security group.
- Route tables and network ACLs must permit the connection.
- DNS must resolve the SQL Server endpoint.
- The Glue job must have connectivity to S3 and any required AWS service APIs.
For Glue jobs attached to a VPC, configure the necessary S3 endpoint and other connectivity for the job's dependencies.
8. Private Subnet Architecture
A secure architecture keeps SQL Server in a private subnet.
AWS VPC | +----------+----------+ | | v v Private DB Subnet Glue Job ENIs | | v | Windows EC2 | SQL Server <---------------+ | v S3 Gateway Endpoint | v Amazon S3 | v AWS Glue | v Amazon AthenaThe S3 gateway endpoint provides private connectivity to S3 from associated VPC route tables.
It does not automatically provide connectivity to Athena, Glue APIs, Secrets Manager, CloudWatch Logs, or Systems Manager.
Where needed, configure supported interface VPC endpoints or another approved network path.
9. Create the S3 Data Lake Structure
A recommended structure:
s3://company-sqlserver-archive/ raw/ salesdb/ orders/ curated/ salesdb/ orders/ year=2024/ month=01/ year=2024/ month=02/ year=2025/ month=01/
s3://company-athena-results/ queries/The raw zone can preserve extracted source records.
The curated zone contains validated, transformed, analytics-ready datasets.
Use separate locations for source extracts and queryable Parquet datasets.
10. Create an AWS Glue JDBC Connection
In the AWS Glue console:
- Open Data connections.
- Create a connection for Microsoft SQL Server.
- Enter the JDBC connection information.
- Select the VPC and private subnet.
- Configure a suitable security group.
- Configure database authentication.
- Store credentials using an approved secret-management mechanism.
- Test connectivity.
Connection configuration and Glue console labels can vary by supported Glue version.
11. AWS Glue PySpark ETL Example
The following example extracts historical SQL Server orders and writes them to S3 in Parquet format.
import sysfrom awsglue.utils import getResolvedOptionsfrom pyspark.context import SparkContextfrom awsglue.context import GlueContextfrom pyspark.sql.functions import year, month, col
args = getResolvedOptions( sys.argv, ["JOB_NAME", "ARCHIVE_CUTOFF"])
sc = SparkContext()glue_context = GlueContext(sc)spark = glue_context.spark_session
cutoff = args["ARCHIVE_CUTOFF"]
query = f"""( SELECT OrderID, CustomerID, OrderDate, TotalAmount, OrderStatus FROM dbo.Orders WHERE OrderDate < '{cutoff}') AS archived_orders"""
orders_df = ( spark.read .format("jdbc") .option( "url", "jdbc:sqlserver://sqlserver.internal:1433;" "databaseName=SalesDB;" "encrypt=true;" "trustServerCertificate=false" ) .option("dbtable", query) .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") .option("user", "REPLACE_WITH_SECURE_USERNAME") .option("password", "REPLACE_WITH_SECURE_PASSWORD") .load())
orders_df = ( orders_df .withColumn("year", year(col("OrderDate"))) .withColumn("month", month(col("OrderDate"))))
( orders_df.write .mode("append") .partitionBy("year", "month") .parquet( "s3://company-sqlserver-archive/" "curated/salesdb/orders/" ))Production note: This is an illustrative extraction pattern. Never hardcode database credentials in production. Retrieve them securely through an approved Glue connection or Secrets Manager integration.
The SQL Server JDBC driver must be available in the Glue runtime. Validate supported driver versions, data types, and job configuration.
The cutoff should be validated as a timestamp before constructing a SQL query. Prefer a controlled, fixed cutoff from an approved archival manifest.
Repeated
append runs can duplicate records. Implement incremental extraction, deduplication, or a controlled partition replacement strategy.12. Why Convert SQL Server Data to Parquet?
Parquet is a columnar storage format well suited for analytical queries.
Advantages include:
- Column-oriented reads
- Compression
- Reduced S3 storage consumption
- Reduced Athena data scanning
- Efficient aggregation queries
- Compatibility with Glue and Athena
Example:
SQL Server Rows | vAWS Glue Transformation | vParquet Files | vPartitioned S3 Storage | vAthena SQL QueriesAvoid generating excessive numbers of tiny files. File size and partition design affect query performance and operational overhead.
13. Partitioning Strategy
Partitioning improves query efficiency when queries filter on partition columns.
Example:
orders/ year=2024/ month=01/ part-00001.parquet month=02/ part-00002.parquetExample Athena query:
SELECT *FROM sales_archive.ordersWHERE year = 2024 AND month = 1;Partition column types must match the Glue Data Catalog definition.
Partition pruning reduces unnecessary file scanning when queries use suitable filters.
14. AWS Glue Data Catalog
The Glue Data Catalog stores metadata about datasets, including:
- Database names
- Table names
- Column definitions
- Storage locations
- Partition information
- Data formats
Example:
Glue Data Catalog | vDatabase: sales_archive | vTable: orders | +--> OrderID +--> CustomerID +--> OrderDate +--> TotalAmount +--> OrderStatus +--> year +--> monthYou can create catalog tables through Glue crawlers or explicit table definitions.
For production, use controlled schema evolution and validate inferred column types.
15. Create a Glue Crawler
Configure a crawler to scan the curated Parquet location:
s3://company-sqlserver-archive/ curated/salesdb/orders/Choose the appropriate Glue IAM role and target Data Catalog database.
Run the crawler after the ETL job completes successfully.
Review the resulting table schema and partition metadata.
For large partitioned datasets, consider explicit partition registration or partition projection when appropriate.
16. Query Archived SQL Server Data with Athena
Once the catalog table exists, Athena can query the archived data.
Example:
SELECT OrderID, CustomerID, OrderDate, TotalAmountFROM sales_archive.ordersWHERE year = 2024 AND month = 1ORDER BY OrderDate DESCLIMIT 100;Aggregate historical orders
SELECT year, month, COUNT(*) AS total_orders, SUM(TotalAmount) AS total_revenueFROM sales_archive.ordersGROUP BY year, monthORDER BY year, month;Search by customer
SELECT OrderID, OrderDate, TotalAmount, OrderStatusFROM sales_archive.ordersWHERE CustomerID = 10001 AND year = 2024;Athena query execution is asynchronous.
Applications should submit queries, monitor execution status, and retrieve results only after successful completion.
17. Search Archived Data from Windows EC2
A Windows application can query Athena using a supported AWS SDK, JDBC driver, ODBC driver, or backend API.
Windows Application EC2 | v Search Request | v Athena API | v Glue Data Catalog | v Amazon S3 Parquet | v Query Results | v Windows ApplicationFor private networking, configure the required Athena interface endpoint and S3 gateway endpoint, plus Glue connectivity if the application directly uses Glue APIs.
Use an EC2 IAM role with least-privilege access.
Athena is suitable for historical queries, not high-frequency transactional updates.
18. Data Validation Before Removing SQL Server Records
This is one of the most important stages.
Do not delete historical records immediately after an AWS Glue job reports success.
Validate:
- SQL Server source row counts.
- Extracted row counts.
- Curated Parquet row counts.
- Athena query results.
- Data types and null values.
- Primary-key uniqueness.
- Financial totals and other critical aggregates.
- Date ranges and timezone handling.
- Archive access permissions.
- Recovery and reprocessing procedures.
Example SQL Server validation:
SELECT COUNT_BIG(*) AS TotalOrders, SUM(TotalAmount) AS TotalAmountFROM dbo.OrdersWHERE OrderDate < '2024-01-01';Example Athena validation:
SELECT COUNT(*) AS TotalOrders, SUM(TotalAmount) AS TotalAmountFROM sales_archive.ordersWHERE year < 2024;Ensure the two queries represent exactly the same record set before comparing results.
Once archival is verified, use an approved deletion or partition-management process that respects foreign keys, retention rules, and transactional consistency.
19. Incremental Archival Strategy
Full extraction is suitable for an initial migration but may be inefficient for ongoing archival.
A production pipeline can use:
- A fixed archival cutoff
- A persisted extraction watermark
- A stable primary key
- Change tracking or CDC where needed
- Idempotent writes
- A job execution manifest
- Retry and reconciliation logic
Initial Historical Load | v Validate Archive | v Save Watermark | v Scheduled Incremental Job | v Extract New History | v Update S3 Dataset | v Validate and CommitIf historical rows can be updated after their original creation, a date-only watermark may miss changes.
In that case, consider SQL Server change tracking, CDC, or AWS DMS as an extraction mechanism.
AWS Glue remains useful for downstream transformation and cataloging.
20. Security Architecture
Recommended controls:
- Private SQL Server EC2 subnet
- Restricted SQL Server security group
- IAM roles for Glue jobs
- S3 Block Public Access
- S3 default encryption
- KMS key permissions where applicable
- Secrets Manager for database credentials
- TLS for JDBC connections
- Glue Data Catalog permissions
- Lake Formation governance where needed
- CloudTrail logging
- S3 access logging or appropriate audit events
- Controlled Athena workgroups
Avoid exposing SQL Server to the public internet for ETL connectivity.
21. Monitoring and Error Handling
Monitor:
- Glue job execution status
- Glue job duration
- Extracted record counts
- Failed partitions
- SQL Server connection failures
- JDBC timeouts
- S3 write errors
- Athena query failures
- Data reconciliation failures
- Archive storage growth
- Job cost
Use CloudWatch alarms and EventBridge-based notifications.
For production, distinguish between transient failures and permanent data-quality errors.
22. Cost Optimization
Key cost components include:
- Windows EC2 and SQL Server licensing
- EBS storage
- AWS Glue compute
- Amazon S3 storage
- Glue Data Catalog usage
- Athena data scanned
- KMS requests where applicable
- Monitoring and networking
Cost optimization techniques:
Parquet: Reduce the volume of data scanned by Athena.
Partitioning: Filter by relevant year, month, or business dimension.
Incremental ETL: Avoid repeatedly extracting the full historical database.
Efficient file sizing: Avoid excessive small files.
Lifecycle policies: Move older objects to appropriate storage classes, considering retrieval requirements.
Athena workgroups: Configure query controls and usage monitoring.
Do not transition frequently queried Athena data into storage classes that require restoration before access.
23. Terraform Project Structure
terraform/ modules/ ec2-sqlserver/ glue-connections/ glue-jobs/ s3-data-lake/ s3-vpc-endpoint/ iam/ kms/ athena/ monitoring/ environments/ dev/ staging/ production/Use Terraform to provision the supporting infrastructure.
Use CI/CD to validate and deploy Glue scripts, catalog definitions, IAM policies, and monitoring resources.
Store database credentials outside Terraform source code and avoid exposing secrets in Terraform state.
24. Practical AWS Project
Project: SQL Server Historical Data Archival and Search Platform
Goal: Reduce historical data stored in SQL Server while preserving searchable access through S3 and Athena.
Technology stack
- Windows Server on Amazon EC2
- Microsoft SQL Server
- AWS Glue
- Amazon S3
- Amazon Athena
- AWS Glue Data Catalog
- AWS Secrets Manager
- AWS IAM
- AWS KMS
- Amazon CloudWatch
- AWS Systems Manager
- Terraform
- GitHub Actions
Implementation phases
Phase 1 — Discovery
Identify tables, data volumes, retention requirements, and dependencies.
Phase 2 — Networking
Configure private Glue connectivity to SQL Server and S3.
Phase 3 — Initial extraction
Export a fixed historical data range.
Phase 4 — Transformation
Clean and convert data into partitioned Parquet.
Phase 5 — Catalog
Register datasets using AWS Glue.
Phase 6 — Athena
Create and test historical search queries.
Phase 7 — Validation
Reconcile source and archived datasets.
Phase 8 — Incremental automation
Schedule recurring archival jobs.
Phase 9 — Application integration
Allow the Windows application to query historical records.
Phase 10 — Controlled cleanup
Remove eligible SQL Server data only after verification and approval.
25. Production Readiness Checklist
- SQL Server source tables and dependencies documented.
- Historical retention policy approved.
- SQL Server remains in a private subnet.
- Glue JDBC connection tested.
- Database credentials stored securely.
- S3 endpoint connectivity verified.
- Raw and curated S3 zones created.
- Parquet schema and data types validated.
- Partitioning strategy implemented.
- Glue Data Catalog tables verified.
- Athena queries tested.
- Source and archive row counts reconciled.
- Incremental archival is idempotent.
- S3 encryption and IAM permissions configured.
- CloudWatch alerts enabled.
- Backup and recovery procedures tested.
- Source deletion requires formal approval.
- Cost monitoring configured.
- Terraform and ETL scripts version-controlled.
26. Key Takeaway
Migrating historical Microsoft SQL Server data from Windows EC2 into Amazon S3 using AWS Glue and Athena is an effective strategy for separating transactional workloads from long-term analytics.
The complete architecture is:
Microsoft SQL Server on Windows EC2 → AWS Glue JDBC Extraction → S3 Parquet Data Lake → Glue Data Catalog → Amazon Athena → Historical Search
The critical success factors are secure connectivity, correct data types, reliable incremental processing, reconciliation, and carefully controlled deletion of source records.
Amazon S3 stores the history. AWS Glue prepares and catalogs the data. Amazon Athena makes the history searchable. SQL Server continues to serve live business transactions.
Official AWS References
Final Thought: A successful SQL Server archival project is not complete when the data reaches S3. It is complete when the data is verified, governed, searchable, recoverable, and safely removed from the transactional database according to policy.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article