Book consult
    Azure

    Azure Synapse Analytics: Unified Analytics Platform Deep Dive

    Prasanna Ravikumar
    October 25, 2024
    Azure Synapse Analytics: Unified Analytics Platform Deep Dive

    Explore Azure Synapse Analytics, Microsoft's unified platform that brings together data warehousing, big data, and data integration in a single, powerful service.

    Azure Synapse Analytics: Unified Analytics Platform Deep Dive

    Azure Synapse Analytics represents a paradigm shift in cloud data platforms, unifying enterprise data warehousing, big data analytics, and data integration into a single, cohesive service. This comprehensive guide explores how to leverage Synapse for modern analytics workloads.

    What is Azure Synapse Analytics?

    Azure Synapse is Microsoft's unified analytics service that combines:

    - SQL Data Warehousing - Massively parallel processing (MPP) architecture - Apache Spark - Distributed big data processing - Data Integration - Built-in ETL/ELT pipelines - Power BI Integration - Seamless visualization - Azure ML Integration - Machine learning workflows

    Why Synapse?

    Traditional Approach: - Separate data warehouse (SQL DW) - Separate Spark cluster (Databricks/HDInsight) - Separate ETL tool (Data Factory) - Complex integration and management

    Synapse Approach: - Single unified workspace - Integrated development experience - Shared metadata and security - Pay only for what you use

    Core Architecture

    Workspace Components

    ``` Synapse Workspace ├── SQL Pools (Dedicated & Serverless) ├── Apache Spark Pools ├── Data Integration (Pipelines) ├── Data Explorer (Kusto) ├── Linked Services └── Managed VNET ```

    Data Lake Integration

    ``` Azure Data Lake Gen2 ├── Bronze Layer (Raw data) ├── Silver Layer (Cleaned/Transformed) └── Gold Layer (Business aggregates) ↓ Synapse SQL Serverless ↓ Power BI Reports ```

    SQL Pools: Data Warehousing

    Dedicated SQL Pool (formerly SQL DW)

    Architecture: - 60 distributions - Massively parallel processing - Columnar storage - Adaptive caching

    Example: Creating a Dedicated Pool

    ```sql -- Create dedicated SQL pool CREATE DATABASE SalesDW ( SERVICE_OBJECTIVE = 'DW1000c', MAXSIZE = 240 GB );

    -- Create fact table with distribution CREATE TABLE dbo.FactSales ( SaleID INT NOT NULL, DateKey INT NOT NULL, ProductKey INT NOT NULL, CustomerKey INT NOT NULL, Quantity INT NOT NULL, Revenue DECIMAL(18,2) NOT NULL, Cost DECIMAL(18,2) NOT NULL ) WITH ( CLUSTERED COLUMNSTORE INDEX, DISTRIBUTION = HASH(SaleID) );

    -- Create dimension table with replication CREATE TABLE dbo.DimProduct ( ProductKey INT NOT NULL, ProductName NVARCHAR(100) NOT NULL, Category NVARCHAR(50) NOT NULL, ListPrice DECIMAL(18,2) NOT NULL ) WITH ( CLUSTERED COLUMNSTORE INDEX, DISTRIBUTION = REPLICATE ); ```

    Optimization Patterns:

    ```sql -- Partitioning for large tables CREATE TABLE dbo.FactSalesPartitioned ( SaleID INT NOT NULL, DateKey INT NOT NULL, Revenue DECIMAL(18,2) ) WITH ( CLUSTERED COLUMNSTORE INDEX, DISTRIBUTION = HASH(SaleID), PARTITION ( DateKey RANGE RIGHT FOR VALUES (20230101, 20230201, 20230301, 20230401) ) );

    -- Statistics for query optimization CREATE STATISTICS stat_sales_date ON dbo.FactSales(DateKey);

    CREATE STATISTICS stat_sales_product ON dbo.FactSales(ProductKey); ```

    Serverless SQL Pool

    Use Cases: - Query data lake files directly - Data exploration - Logical data warehouse - Ad-hoc analysis

    Example: Query Parquet Files

    ```sql -- Query Parquet files in Data Lake SELECT YEAR(OrderDate) as OrderYear, MONTH(OrderDate) as OrderMonth, SUM(Amount) as TotalRevenue, COUNT() as OrderCount FROM OPENROWSET( BULK 'https://mydatalake.dfs.core.windows.net/sales/2024//.parquet', FORMAT = 'PARQUET' ) AS [sales] GROUP BY YEAR(OrderDate), MONTH(OrderDate) ORDER BY OrderYear, OrderMonth;

    -- Create external table for reusable queries CREATE EXTERNAL DATA SOURCE SalesDataLake WITH ( LOCATION = 'https://mydatalake.dfs.core.windows.net/sales' );

    CREATE EXTERNAL FILE FORMAT ParquetFormat WITH ( FORMAT_TYPE = PARQUET, DATA_COMPRESSION = 'org.apache.hadoop.io.compress.SnappyCodec' );

    CREATE EXTERNAL TABLE dbo.Sales ( OrderID INT, OrderDate DATE, CustomerID INT, Amount DECIMAL(18,2) ) WITH ( LOCATION = '2024//.parquet', DATA_SOURCE = SalesDataLake, FILE_FORMAT = ParquetFormat );

    -- Now query like a regular table SELECT FROM dbo.Sales WHERE OrderDate >= '2024-01-01'; ```

    Apache Spark Pools

    Configuration

    ```python Create Spark pool via Azure CLI az synapse spark pool create \\ --name sparkpool1 \\ --workspace-name mysynapse \\ --resource-group myResourceGroup \\ --spark-version 3.3 \\ --node-count 3 \\ --node-size Medium \\ --enable-auto-scale true \\ --min-node-count 3 \\ --max-node-count 10 ```

    PySpark Example: ETL Pipeline

    ```python Import libraries from pyspark.sql import SparkSession from pyspark.sql.functions import from pyspark.sql.types import

    Create Spark session (automatically available in Synapse notebooks) spark = SparkSession.builder.appName("ETL").getOrCreate()

    Read from Data Lake df_raw = spark.read.parquet( "abfss://raw@mydatalake.dfs.core.windows.net/sales/.parquet" )

    Data quality checks df_clean = (df_raw .filter(col("Amount") > 0) .filter(col("OrderDate").isNotNull()) .dropDuplicates(["OrderID"]) )

    Transformations df_transformed = (df_clean .withColumn("OrderYear", year("OrderDate")) .withColumn("OrderMonth", month("OrderDate")) .withColumn("OrderQuarter", quarter("OrderDate")) .withColumn("RevenueCategory", when(col("Amount") > 10000, "High") .when(col("Amount") > 1000, "Medium") .otherwise("Low")) )

    Aggregate metrics df_aggregated = (df_transformed .groupBy("OrderYear", "OrderMonth", "CustomerID") .agg( sum("Amount").alias("TotalRevenue"), count("OrderID").alias("OrderCount"), avg("Amount").alias("AvgOrderValue"), max("OrderDate").alias("LastOrderDate") ) )

    Write to curated layer (df_aggregated .write .mode("overwrite") .partitionBy("OrderYear", "OrderMonth") .parquet("abfss://curated@mydatalake.dfs.core.windows.net/sales_aggregated") )

    Write to Delta Lake for ACID transactions (df_transformed .write .format("delta") .mode("overwrite") .partitionBy("OrderYear", "OrderMonth") .save("abfss://curated@mydatalake.dfs.core.windows.net/sales_delta") ) ```

    Spark SQL Integration

    ```python Register as temporary view df_transformed.createOrReplaceTempView("sales_view")

    Query using Spark SQL result = spark.sql(""" SELECT OrderYear, RevenueCategory, SUM(Amount) as TotalRevenue, COUNT(DISTINCT CustomerID) as UniqueCustomers FROM sales_view WHERE OrderYear = 2024 GROUP BY OrderYear, RevenueCategory ORDER BY TotalRevenue DESC """)

    result.show()

    Write results to Synapse SQL Pool (result .write .mode("overwrite") .synapsesql("SalesDW.dbo.RevenueByCategory", tabletype="managed") ) ```

    Data Integration (Pipelines)

    Creating ETL Pipeline

    ```json { "name": "IncrementalCopyPipeline", "activities": [ { "name": "LookupLastWatermark", "type": "Lookup", "outputs": [{"referenceName": "WatermarkTable"}], "typeProperties": { "source": { "type": "AzureSqlSource", "sqlReaderQuery": "SELECT MAX(LastModifiedDate) as WatermarkValue FROM [dbo].[Watermark]" } } }, { "name": "CopyIncrementalData", "type": "Copy", "dependsOn": [{"activity": "LookupLastWatermark"}], "inputs": [{"referenceName": "SourceDataset"}], "outputs": [{"referenceName": "SinkDataset"}], "typeProperties": { "source": { "type": "SqlSource", "sqlReaderQuery": { "value": "@concat('SELECT FROM Sales WHERE LastModifiedDate > '', activity('LookupLastWatermark').output.firstRow.WatermarkValue, '')", "type": "Expression" } }, "sink": { "type": "ParquetSink" } } }, { "name": "UpdateWatermark", "type": "SqlServerStoredProcedure", "dependsOn": [{"activity": "CopyIncrementalData"}], "typeProperties": { "storedProcedureName": "usp_UpdateWatermark" } } ] } ```

    Advanced Features

    1. Lake Database

    ```sql -- Create Lake Database (metadata over Data Lake) CREATE DATABASE LakeSales;

    -- Create lake table CREATE EXTERNAL TABLE LakeSales.dbo.Sales ( OrderID INT, OrderDate DATE, Amount DECIMAL(18,2) ) WITH ( LOCATION = '/sales/', DATA_SOURCE = DataLakeSource, FILE_FORMAT = ParquetFormat );

    -- Query seamlessly across SQL and Spark SELECT FROM LakeSales.dbo.Sales; ```

    2. Synapse Link for Cosmos DB

    ```python Read from Cosmos DB analytical store in real-time df_cosmos = (spark.read .format("cosmos.olap") .option("spark.synapse.linkedService", "CosmosDBLinkedService") .option("spark.cosmos.container", "Orders") .load() )

    Analyze transactional data in near real-time df_analytics = (df_cosmos .filter(col("status") == "completed") .groupBy(window("timestamp", "1 hour")) .agg( sum("amount").alias("hourly_revenue"), count("").alias("order_count") ) )

    df_analytics.show() ```

    3. Dedicated SQL Pool Workload Management

    ```sql -- Create workload group CREATE WORKLOAD GROUP DataScientists WITH ( MIN_PERCENTAGE_RESOURCE = 20, CAP_PERCENTAGE_RESOURCE = 40, REQUEST_MIN_RESOURCE_GRANT_PERCENT = 2 );

    -- Create workload classifier CREATE WORKLOAD CLASSIFIER DataScienceQueries WITH ( WORKLOAD_GROUP = 'DataScientists', MEMBERNAME = 'DataScienceUser', IMPORTANCE = HIGH ); ```

    Security and Governance

    Row-Level Security

    ```sql -- Create security predicate function CREATE FUNCTION dbo.fn_SecurityPredicate(@Region AS NVARCHAR(50)) RETURNS TABLE WITH SCHEMABINDING AS RETURN SELECT 1 AS fn_SecurityPredicate_result WHERE @Region = USER_NAME() OR USER_NAME() = 'Admin';

    -- Apply security policy CREATE SECURITY POLICY SalesFilter ADD FILTER PREDICATE dbo.fn_SecurityPredicate(Region) ON dbo.FactSales WITH (STATE = ON); ```

    Column-Level Security

    ```sql -- Grant column permissions GRANT SELECT ON dbo.Customer(CustomerID, Name, Email) TO DataAnalyst; DENY SELECT ON dbo.Customer(SSN, CreditCard) TO DataAnalyst; ```

    Dynamic Data Masking

    ```sql -- Apply data masking ALTER TABLE dbo.Customer ALTER COLUMN Email ADD MASKED WITH (FUNCTION = 'email()');

    ALTER TABLE dbo.Customer ALTER COLUMN Phone ADD MASKED WITH (FUNCTION = 'partial(0,"XXX-XXX-",4)'); ```

    Performance Optimization

    Best Practices

    1. Choose Right Distribution - Hash for large fact tables (on join key) - Replicate for small dimension tables (<2GB) - Round-robin for staging tables

    2. Partition Strategically - Partition large tables (>1 billion rows) - Use date-based partitioning - Limit to 100 partitions

    3. Use Result Set Caching

    ```sql -- Enable result set caching SET RESULT_SET_CACHING ON;

    -- Cache results for repeated queries SELECT Region, SUM(Revenue) FROM FactSales GROUP BY Region; ```

    4. Materialized Views

    ```sql CREATE MATERIALIZED VIEW dbo.MV_SalesSummary WITH (DISTRIBUTION = HASH(ProductKey)) AS SELECT ProductKey, YEAR(OrderDate) AS OrderYear, SUM(Revenue) AS TotalRevenue, COUNT() AS OrderCount FROM dbo.FactSales GROUP BY ProductKey, YEAR(OrderDate);

    -- Auto-refresh when base tables change ```

    Cost Optimization

    Pause/Resume Dedicated SQL Pools

    ```python Using Azure SDK from azure.mgmt.synapse import SynapseManagementClient

    synapse_client = SynapseManagementClient(credential, subscription_id)

    Pause during off-hours synapse_client.sql_pools.pause( resource_group_name="myResourceGroup", workspace_name="mysynapse", sql_pool_name="SalesDW" )

    Resume before business hours synapse_client.sql_pools.resume( resource_group_name="myResourceGroup", workspace_name="mysynapse", sql_pool_name="SalesDW" ) ```

    Serverless SQL - Pay Per Query

    ```sql -- Optimize data formats (Parquet > CSV) -- Use partitioning to scan less data -- Apply filters early in queries

    SELECT FROM OPENROWSET( BULK '/sales/year=2024/month=10/.parquet', DATA_SOURCE = 'DataLake', FORMAT = 'PARQUET' ) AS sales WHERE Amount > 1000; -- Filter reduces data scanned ```

    Monitoring and Troubleshooting

    Query Performance Insights

    ```sql -- View running queries SELECT FROM sys.dm_pdw_exec_requests WHERE status = 'Running';

    -- Analyze query execution plan SELECT FROM sys.dm_pdw_request_steps WHERE request_id = 'QID12345';

    -- Identify slow operations SELECT request_id, step_index, operation_type, row_count, total_elapsed_time FROM sys.dm_pdw_request_steps WHERE request_id = 'QID12345' ORDER BY total_elapsed_time DESC; ```

    Real-World Use Cases

    Retail Analytics - Real-time inventory tracking - Customer 360 analysis - Demand forecasting - Price optimization

    Financial Services - Fraud detection - Risk modeling - Regulatory reporting - Customer analytics

    Healthcare - Patient outcomes analysis - Operational efficiency - Clinical trial data analysis - Population health management

    Conclusion

    Azure Synapse Analytics represents the future of cloud analytics platforms, combining the best of data warehousing, big data, and data integration. Its unified approach reduces complexity, improves productivity, and enables organizations to unlock insights faster than ever before.

    Key takeaways: - Start with Serverless SQL for exploration - Use Dedicated SQL Pools for production workloads - Leverage Spark for complex transformations - Integrate tightly with Power BI for visualization - Optimize for cost with pause/resume and serverless options

    Whether you're building a new analytics platform or migrating from traditional solutions, Azure Synapse provides the scalability, performance, and flexibility needed for modern data workloads.

    Share this article