Symptom
A job that writes a Delta table out to Azure SQL Database for an app or a report does one of these:
- It runs for hours to push a few million rows, while the Spark cluster sits mostly idle.
- Tasks fail with
Transaction (Process ID nn) was deadlocked on lock resources(error 1205). - It fails with error 40501 (
The service is currently busy) or 40613 (Database ... is not currently available). - After a
mode("overwrite")run, the target table has lost its indexes, permissions and column types. Strings are nowNVARCHAR(MAX). - A rerun of a failed job leaves duplicate rows in the target.
Most of these trace back to one decision: how many partitions write in parallel and what each one sends. The other cause is what overwrite actually does to the table.
Quick checks
1. How many parallel writers does Spark open?
Spark opens one JDBC connection per partition of the DataFrame you write. Count the partitions without using the RDD API, which is blocked on standard access mode and serverless:
from pyspark.sql import functions as F
print(df.select(F.spark_partition_id().alias("p")).distinct().count())
One partition means one connection writing serially. Hundreds of partitions mean hundreds of sessions fighting over the same table.
2. Is Azure SQL the bottleneck?
Run this on the target database while the job is writing. The view keeps one row per 15 seconds for about an hour:
SELECT TOP (20) end_time, avg_cpu_percent, avg_data_io_percent,
avg_log_write_percent, max_worker_percent, max_session_percent
FROM sys.dm_db_resource_stats
ORDER BY end_time DESC;
If avg_log_write_percent sits near 100, the service tier's log rate cap is the limit, and more Spark parallelism will make things worse. If every value is low, the problem is on the Spark side (too few partitions or tiny batches).
3. Who is blocking whom?
SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time,
r.command, s.program_name, t.text
FROM sys.dm_exec_requests AS r
JOIN sys.dm_exec_sessions AS s ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
WHERE s.is_user_process = 1
ORDER BY r.blocking_session_id DESC;
To make the Spark sessions easy to spot, add applicationName=<job-name> to the JDBC URL. Without it, they show up as Microsoft JDBC Driver for SQL Server.
Symptom → cause → fix
| Symptom | Likely cause | Fix |
|---|---|---|
| Slow, Azure SQL mostly idle | One or few partitions, default batchsize of 1000 | Repartition to 4–16, raise batchsize, enable bulk copy |
Slow, avg_log_write_percent near 100 | Service tier log rate cap | Fewer writers, load into a heap staging table, scale the database up for the load window |
| Error 1205 deadlocks | Many partitions inserting into the same clustered or nonclustered indexes | Fewer partitions, write to a heap staging table, then run one INSERT ... SELECT or MERGE |
| Error 40501 | Azure SQL throttling the database | Reduce parallelism, retry with backoff, check tier |
| Error 40613 on first connect | Serverless Azure SQL resuming from auto-pause, or failover | Retry; for scheduled loads, disable auto-pause or wake the database first |
| Indexes and grants gone after overwrite | overwrite drops and recreates the table | truncate=true, or pre-create the table and append |
String or binary data would be truncated (2628 or 8152) | Source values longer than the target column | Find the long values in Spark, widen the column or trim deliberately |
| Duplicates after a rerun | append isn't idempotent | Staging table plus MERGE, or delete the load window first |
Fix 1: control parallelism and batch size
Pick the writer count from what the database can absorb, not from the cluster size. Start with 4 to 8 for General Purpose tiers and measure against sys.dm_db_resource_stats.
jdbc_url = (
"jdbc:sqlserver://<server>.database.windows.net:1433;"
"database=<db>;encrypt=true;trustServerCertificate=false;"
"hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
"applicationName=sales-export;"
"useBulkCopyForBatchInsert=true"
)
(df.repartition(8)
.write.format("jdbc")
.option("url", jdbc_url)
.option("dbtable", "stg.sales_load")
.option("user", dbutils.secrets.get("kv-sql", "sql-user"))
.option("password", dbutils.secrets.get("kv-sql", "sql-password"))
.option("batchsize", 10000)
.mode("append")
.save())
repartition(n)sets the number of concurrent connections.coalesce(n)also works when you're only reducing partitions, and it avoids a shuffle.batchsizesets how many rows go in each JDBC batch. The default is 1000. Values of 5,000 to 50,000 usually help, but larger batches hold locks longer.useBulkCopyForBatchInsert=trueis a Microsoft JDBC driver property (driver 9.2 and later) that turns batched inserts into bulk copy operations. It often gives the biggest speed-up. It has data type and trigger limitations, so test it against your table first and check which driver version your runtime bundles.
On serverless compute, use the bundled sqlserver format (options host, database, dbtable, user, password, batchsize, numPartitions, truncate, isolationLevel). It supports only a subset of options and doesn't accept custom driver JARs, so check the current option list before you rely on driver-level properties there.
Tip
When the source is a large Delta table, filter and select the columns first. Spark reads, serializes and sends every column you leave in the DataFrame, even columns the target table ignores.
Fix 2: stop overwrite from dropping the table
By default, mode("overwrite") drops the target table and recreates it from the DataFrame schema. You lose clustered and nonclustered indexes, constraints, grants and column lengths, and Spark picks generic types.
Warning
Any app, view or report that depends on the table's indexes or permissions breaks after the first default overwrite. Users see permission errors or very slow queries, not a failed load.
Keep the table definition and only replace the rows:
(df.write.format("jdbc")
.option("url", jdbc_url)
.option("dbtable", "dbo.sales_summary")
.option("user", user).option("password", pwd)
.option("truncate", "true")
.mode("overwrite")
.save())
TRUNCATE TABLE needs ALTER permission on the table, and it fails if a foreign key references the table. Create target tables yourself in T-SQL with the right types and lengths. Never let Spark create production tables.
Fix 3: deadlocks and duplicates, staging plus MERGE
When parallel inserts deadlock on indexes, or reruns must not duplicate rows, split the load into two steps:
- Spark appends into a staging table with no indexes (a heap), which parallel inserts handle well.
- One set-based statement in Azure SQL moves the rows into the real table.
CREATE OR ALTER PROCEDURE dbo.usp_merge_sales_load
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRAN;
MERGE dbo.sales WITH (HOLDLOCK) AS tgt
USING stg.sales_load AS src
ON tgt.order_id = src.order_id
WHEN MATCHED THEN
UPDATE SET tgt.amount = src.amount, tgt.updated_at = src.updated_at
WHEN NOT MATCHED THEN
INSERT (order_id, amount, updated_at)
VALUES (src.order_id, src.amount, src.updated_at);
TRUNCATE TABLE stg.sales_load;
COMMIT;
END;
Run the procedure as the next step after the write. You can call it from an Azure Data Factory Stored Procedure activity that runs after the Databricks activity, or from a small Python task in the same job that connects through a SQL Server driver you install (for example pyodbc with the Microsoft ODBC driver). Because the procedure is keyed on order_id, a rerun updates rows instead of duplicating them. Truncate the staging table at the start of the Spark step too, so a half-finished earlier run can't leak in.
Fix 4: truncation errors
Find the values that don't fit before you write:
from pyspark.sql import functions as F
df.select([F.max(F.length(c)).alias(c)
for c, t in df.dtypes if t == "string"]).show(vertical=True)
Compare the results with the column lengths in the target:
SELECT c.name, ty.name AS type_name, c.max_length
FROM sys.columns AS c
JOIN sys.types AS ty ON c.user_type_id = ty.user_type_id
WHERE c.object_id = OBJECT_ID('dbo.sales_summary');
max_length is in bytes, so NVARCHAR(100) shows as 200. Widen the column, or trim in Spark with substring if the business agrees that truncating is acceptable.
Prevent it next time
- Pre-create every target table and use
appendortruncate=true. Don't use a plainoverwrite. - Set the writer count on purpose with
repartitionand record it in the job code, next to the database tier it was sized for. - Make every export idempotent: a staging table plus a keyed
MERGE, or delete the load window before inserting. - Put
applicationNamein every JDBC URL so the DBA can identify the job from blocking and Query Store data. - If the database is serverless with auto-pause, schedule loads when it's already awake or disable auto-pause, and add task retries for 40613 and 40501.
- Alert on job duration, not only failure. A write that drifts from 10 minutes to 2 hours usually means the target tier or the indexes changed.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get