Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
Two Apex test classes colliding on one record, causing UNABLE_TO_LOCK_ROW in parallel Apex tests
Apex

UNABLE_TO_LOCK_ROW in Parallel Apex Tests: Fix the Test Data

Random UNABLE_TO_LOCK_ROW failures in Apex test runs come from two documented test-data problems: shared org records and duplicate unique values. Fix both in the test data and keep parallel on, using IsParallel=true to win back speed if you must disable it for a while.

The short answer

UNABLE_TO_LOCK_ROW in parallel Apex tests comes from tests updating shared org rows under SeeAllData=true, or inserting the same unique or external ID values at once. Build data per test with @TestSetup and a factory that generates unique values, and keep parallel on (or opt cleaned classes back in with @IsTest(IsParallel=true)).

Key takeaways Remove SeeAllData=true from any test that updates records, and build those records in @TestSetup instead. Route every unique or external ID value in tests through one factory method that combines a per-transaction random token with a counter. Leave the org-wide parallel setting alone when a deployment fails, because deployments run their tests serially anyway. If you have to disable parallel testing now, mark each cleaned class @IsTest(IsParallel=true) to get speed back one class at a time. Classes that create User or GroupMember records, enqueue jobs, or use mixed DML objects can't opt in, so plan to refactor them or leave them serial.

Your test run fails on a different class each time with UNABLE_TO_LOCK_ROW, the rerun passes, and someone suggests ticking Disable Parallel Apex Testing to make the noise stop. That checkbox applies to the whole org and slows every run you start, and the defect is still there whenever parallel gets switched back on. A recent r/SalesforceDeveloper thread asked how to avoid exactly this. My answer is to treat the error as a bug in how your tests create data, fix it class by class, and keep parallel execution on.

The two causes, and a repro for each

Salesforce's testing guidance documents two ways parallel tests collide. In both, two test transactions want the same row, or the same unique index entry, at the same moment.

Shared org data under SeeAllData=true

The first cause is tests that don't create their own data. They switch off isolation with SeeAllData=true to reach records already in the org, and when two of them update the same record at once, one waits on the other's lock.

A common version is a single integration config row, fetched with LIMIT 1 and updated by every sync test.

@IsTest(SeeAllData=true)
private class OrderSyncServiceTest {
    @IsTest
    static void marksRunAsInProgress() {
        Integration_Setting__c cfg = [
            SELECT Id, Last_Sync_Status__c
            FROM Integration_Setting__c
            LIMIT 1
        ];
        cfg.Last_Sync_Status__c = 'Running';
        update cfg;

        Test.startTest();
        OrderSyncService.run();
        Test.stopTest();
    }
}

@IsTest(SeeAllData=true)
private class InvoiceSyncServiceTest {
    @IsTest
    static void resetsStatusOnFailure() {
        Integration_Setting__c cfg = [
            SELECT Id, Last_Sync_Status__c
            FROM Integration_Setting__c
            LIMIT 1
        ];
        cfg.Last_Sync_Status__c = 'Failed';
        update cfg; // same physical row as the class above

        Test.startTest();
        InvoiceSyncService.run();
        Test.stopTest();
    }
}

Run both from Setup and they race for that one Integration_Setting__c row. Each test passes when it runs alone, which is why the failure looks random. Drop SeeAllData and give each class its own row:

@IsTest
private class OrderSyncServiceTest {
    @TestSetup
    static void makeData() {
        insert new Integration_Setting__c(
            Name = 'Order Sync',
            Last_Sync_Status__c = 'Idle'
        );
    }

    @IsTest
    static void marksRunAsInProgress() {
        Integration_Setting__c cfg = [
            SELECT Id, Last_Sync_Status__c
            FROM Integration_Setting__c
            LIMIT 1
        ];
        cfg.Last_Sync_Status__c = 'Running';
        update cfg;

        Test.startTest();
        OrderSyncService.run();
        Test.stopTest();
    }
}

Test data never commits, so there is nothing to clean up afterwards. The docs also recommend creating it before Test.startTest(), as shown.

Unique-index deadlocks between tests

The second cause hits teams who have already removed SeeAllData. The docs describe a deadlock when parallel tests create records with duplicate values in a unique index field: each test waits for the other to roll back, and neither can finish.

@IsTest
private class ShipmentRouterTest {
    @IsTest
    static void routesDomesticShipment() {
        insert new Shipment__c(Tracking_Code__c = 'TRK-0001', Country__c = 'US');
        // ...
    }
}

@IsTest
private class ShipmentBillingTest {
    @IsTest
    static void billsOnDelivery() {
        insert new Shipment__c(Tracking_Code__c = 'TRK-0001', Country__c = 'DE');
        // ...
    }
}

Both classes create their own data and neither touches org records. They still collide, because Tracking_Code__c is a unique external ID and both insert the same literal. Hand-typed values like 'TEST-1' or 'ABC123' on unique fields get copied from one class to the next. Once a hardcoded value spreads across several classes, the failure moves around between runs, because which pair collides depends on how the run is scheduled.

A factory that keeps unique values unique

Stop writing unique values by hand. Generate them in one place, and make them distinct across classes as well as within a single class.

@IsTest
public class TestDataFactory {
    private static Integer counter = 0;
    private static final String RUN_TOKEN =
        String.valueOf(Crypto.getRandomInteger()).remove('-');

    public static String uniqueValue(String prefix) {
        counter++;
        return prefix + '-' + RUN_TOKEN + '-' + counter;
    }

    public static Account account() {
        return new Account(Name = uniqueValue('ACC'));
    }

    public static List<Shipment__c> shipments(Id accountId, Integer howMany) {
        List<Shipment__c> rows = new List<Shipment__c>();
        for (Integer i = 0; i < howMany; i++) {
            rows.add(new Shipment__c(
                Account__c = accountId,
                Tracking_Code__c = uniqueValue('TRK'),
                Country__c = 'US'
            ));
        }
        return rows;
    }
}

The counter keeps values apart inside one transaction. Every class starts its counter at the same number, though, so on its own the counter would recreate the collision across classes. The random token is what separates two concurrent classes. A prefix, up to ten digits of token and a counter fit comfortably in a Text(40) field, but check the length of each unique field before you rely on that.

The refactored test then reads like this:

@IsTest
private class ShipmentRouterTest {
    @TestSetup
    static void makeData() {
        Account acct = TestDataFactory.account();
        insert acct;
        insert TestDataFactory.shipments(acct.Id, 5);
    }

    @IsTest
    static void routesDomesticShipment() {
        List<Shipment__c> rows = [
            SELECT Id, Tracking_Code__c FROM Shipment__c WHERE Country__c = 'US'
        ];
        Test.startTest();
        ShipmentRouter.route(rows);
        Test.stopTest();
        for (Shipment__c s : [SELECT Route__c FROM Shipment__c]) {
            Assert.isNotNull(s.Route__c);
        }
    }
}

A workable rule: no SeeAllData on any test that writes, and no unique value in a test that didn't come from the factory. In code review, flag a quoted string assigned to an external ID field the same way you would flag a hardcoded record Id.

Where parallel execution actually applies

According to the docs, tests started from the Salesforce user interface, including the Developer Console, run in parallel. The same page says tests don't run in parallel in metadata deployments, package installations, or change set deployments.

The page names only the UI. It does not say whether runs you start from the CLI or the API follow the same org setting, so treat that as not yet confirmed and compare run times in your own org before and after changing it.

# A run you start yourself
sf apex run test --test-level RunLocalTests --wait 30

# A deployment: its tests run serially per the docs
sf project deploy start --test-level RunLocalTests

Since the org setting doesn't change how deployment tests run, disabling parallel testing to rescue a failing deploy makes no sense. If UNABLE_TO_LOCK_ROW shows up during a deployment, the deploy's tests weren't running in parallel with each other, so look for a different cause. Usually that is a SeeAllData=true test updating a record that a live user, integration or scheduled job is touching at the same moment. The same data fix applies.

Disabling org-wide, then opting clean classes back in

Sometimes a team can't fix two hundred classes this sprint. The documented workaround is in Setup: search for Apex Test, click Options..., tick Disable Parallel Apex Testing in the Apex Test Execution Options dialog, and click OK. The setting covers the entire org.

Many teams assume they can mark one bad class as serial and leave everything else parallel. No such annotation is documented. The control runs the other way: @IsTest(IsParallel=true) forces a class to run in parallel even when the org-wide option is ticked, and lets it run alongside more than the default number of concurrent test classes. So the incremental path is to disable parallel testing for the org, then opt each class back in as you clean it.

@IsTest(IsParallel=true)
private class ShipmentBillingTest {
    @TestSetup
    static void makeData() {
        Account acct = TestDataFactory.account();
        insert acct;
        insert TestDataFactory.shipments(acct.Id, 3);
    }

    @IsTest
    static void billsOnDelivery() {
        // no Users created, no enqueueJob, no mixed DML
    }
}

Opting in comes with restrictions. A class marked IsParallel=true can't call Test.getStandardPricebookId(), System.schedule() or System.enqueueJob(). It can't insert ContentNote, can't create User or GroupMember records, and can't use the setup objects that can't be mixed with other DML. SeeAllData=true and IsParallel=true can't be combined on the same method either. Any class that creates a User for System.runAs is therefore stuck, and runAs tests are common in permission-heavy orgs. Those classes stay serial until parallel is back on for the org.

Option Run speed Effort Fixes root cause Restrictions
Disable parallel org-wide Slowest, every class serial Minutes No None, but every run you start pays
Fix the test data, keep parallel on Fastest Highest up front Yes None beyond normal test rules
Disable org-wide, opt cleaned classes in with IsParallel=true Improves as classes are cleaned Spread over sprints Yes, class by class Opted-in classes can't create Users, enqueue jobs or use mixed DML

I would fix the data and keep parallel on. If a release deadline makes that impossible, use the third row and track how many classes have opted in.

Disabling parallel testing is still the right call in a few situations: a legacy suite built on SeeAllData that nobody can refactor yet, a suite where most classes need Users or mixed DML, or tests that have to touch records you genuinely can't isolate. Write down why you ticked the box and when you plan to revisit it, so it doesn't stay ticked by default.

What to watch for

  • A class-level SeeAllData=true overrides method-level opt-outs, so check the class annotation before assuming a method is isolated.
  • Unique values reused between classes cause deadlocks even when no class reads org data. Search the codebase for quoted strings assigned to external ID and unique fields.
  • The factory's token has to fit the field. A unique field shorter than about 20 characters needs a shorter token or prefix.
  • IsParallel=true keeps a class parallel after you disable parallel testing org-wide. If one of those classes regresses and starts sharing data, the checkbox won't protect you.
  • Deployment tests run serially, so a lock error during a deploy points somewhere other than parallel tests competing with each other.

Originally reported by developer.salesforce.com

Frequently asked questions

why do my apex tests fail randomly with UNABLE_TO_LOCK_ROW

Salesforce documents two causes. Tests may be updating the same org records at the same moment, usually because they use SeeAllData=true, or parallel tests may be inserting records with the same value in a unique index field, which deadlocks them. Which pair of classes collides depends on scheduling, so the failure moves around between runs.

can I make one apex test class run serially

No such annotation is documented. The per-class control works the other way: @IsTest(IsParallel=true) forces a class to run in parallel even when Disable Parallel Apex Testing is ticked for the org.

does disabling parallel apex testing make deployments faster or slower

Neither. The docs state that tests don't run in parallel in metadata deployments, package installations, or change set deployments, so the setting only affects test runs you start yourself.

can I use SeeAllData=true with IsParallel=true

No, the two can't be combined on the same method. A class-level SeeAllData=true also applies to every method in the class, and a method-level SeeAllData=false inside that class is ignored.

how do I generate unique external ID values in apex test data

Put a single factory method in charge of them. Combine a random token generated once per transaction (for example from Crypto.getRandomInteger) with an incrementing counter, so values differ within a class and between classes running at the same time.

Watch the video explainer

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment