Mutate best practices

  • GoogleAdsService.Mutate supports temporary resource names using negative IDs to reference newly created resources within the same request.

  • When using temporary resource names, ensure they are used after being defined, are unique within a single request, and are not remembered across requests.

  • Grouping operations of the same resource type together in your Mutate calls can improve API performance and prevent timeouts.

  • Setting response_content_type to MUTABLE_RESOURCE in your mutate request returns mutable attributes of created or updated objects, avoiding additional search or searchStream requests, but increases the response payload size.

Follow these best practices to optimize performance, manage dependencies across operations, and handle responses when mutating resources in the Google Ads API.

Temporary resource names

Both GoogleAdsService.Mutate and BatchJobService support temporary resource names that can be referenced in subsequent operations. This lets you create a campaign and its associated ad groups, ads, and keywords in a single mutate request or batch job.

To reference a newly created resource within the same mutate request or batch job, specify a negative integer ID (such as -1 or -2, excluding 0) in the new resource's resource_name field. For example, when creating a campaign in a batch request, set its resource name to customers/CUSTOMER_ID/campaigns/-1. When creating an ad group in a later operation within the same request, reference customers/CUSTOMER_ID/campaigns/-1 as the parent campaign. The API automatically replaces -1 with the actual campaign ID generated upon creation.

Usage constraints

Keep the following rules in mind when using temporary resource names:

  • Order matters: You can only reference a temporary resource name after you define it. In a list of operations, the dependent operation (such as creating an ad group) must appear after the operation that creates its parent resource (such as creating a campaign).
  • Single-request or batch-job scope: Temporary resource names do not persist across separate jobs or mutate requests. To reference a resource created in a previous job or mutate request, use its actual system-generated resource name.
  • Global uniqueness: Within a single job or mutate request, each temporary resource name must use a unique negative integer across all resource types. For example, you cannot assign -1 to both a campaign and an ad group in the same request. Reusing a temporary ID within the same request or batch job returns a NewResourceCreationError.DUPLICATE_TEMP_IDS error.

Example payload

Suppose you want to add a campaign, an ad group, and an ad in a single API request or batch job. You can structure the mutateOperations array in a GoogleAdsService.Mutate or BatchJobService.AddBatchJobOperations request payload as shown in the following REST JSON example (with other required resource fields omitted for brevity):

{
  "mutateOperations": [
    {
      "campaignOperation": {
        "create": {
          "resourceName": "customers/CUSTOMER_ID/campaigns/-1"
        }
      }
    },
    {
      "adGroupOperation": {
        "create": {
          "resourceName": "customers/CUSTOMER_ID/adGroups/-2",
          "campaign": "customers/CUSTOMER_ID/campaigns/-1"
        }
      }
    },
    {
      "adGroupAdOperation": {
        "create": {
          "adGroup": "customers/CUSTOMER_ID/adGroups/-2"
        }
      }
    }
  ]
}

This example demonstrates the following key details:

  • The ad group uses a new temporary ID (-2) because -1 is already assigned to the campaign.
  • The ad group references customers/CUSTOMER_ID/campaigns/-1 to link itself to the campaign created in the preceding operation.
  • The adGroupAdOperation references customers/CUSTOMER_ID/adGroups/-2 and omits resourceName because no subsequent operation in the request references the new ad.

Group same-type operations

When using GoogleAdsService.Mutate, group operations together by resource type in the repeated mutate_operations array while respecting parent and child dependencies. This method sequentially reads operations until it encounters a different resource type, and then batches all contiguous operations of the same type into a single backend service request.

For example, if you include 5 campaign operations followed by 10 ad group operations in the repeated mutate_operations field, the system performs two backend calls: one to CampaignService for the 5 campaign operations, and a second to AdGroupService for the 10 ad group operations.

In contrast, interleaving operations by ordering them as [campaign, ad group, campaign, ad group] results in four separate backend calls. Interleaved calls degrade API performance and can lead to request timeouts on large batches.

Handle partial failure and batch limits

By default, GoogleAdsService.Mutate rolls back the entire request if any single operation fails. To commit valid operations even when other operations in the same request fail, set partial_failure to true on the request and inspect partial_failure_error in the response. When partial_failure is true, if a parent operation that defines a temporary ID (such as customers/CUSTOMER_ID/campaigns/-1) fails validation, any dependent child operations referencing that temporary ID in the same request also fail with NewResourceCreationError.TEMP_ID_RESOURCE_HAD_ERRORS. For more details, see the partial failure guide.

Also keep request size, sub-batching, and rate limits in mind:

  • Request and chunk size limits: A single GoogleAdsService.Mutate request enforces a limit of 10,000 mutate operations (or up to 20,000 when all operations in the request are AdGroupCriterionOperations, returning RequestError.TOO_MANY_MUTATE_OPERATIONS if exceeded) and at most 100 action operations (RequestError.TOO_MANY_ACTION_OPERATIONS). BatchJobService.AddBatchJobOperations enforces a maximum of 10,000 operations per call, 10,484,504 bytes per individual MutateOperation, and 41,937,920 bytes per AddBatchJobOperationsRequest (returning BatchJobError.REQUEST_TOO_LARGE if any limit is exceeded, with up to 1,000,000 operations total per batch job). Concurrent mutations targeting the same campaign or account can trigger DatabaseError.CONCURRENT_MODIFICATION errors.
  • BatchJobService atomic sub-batching: Although batch jobs execute under partial-failure semantics (defaulting to 1,000 operations per internal sub-batch), BatchJobService automatically groups certain contiguous dependent operations for the same parent ID into atomic sub-batches:
    • An AssetGroupOperation (create) followed by contiguous AssetGroupAssetOperation (create) operations for the same AssetGroup ID (up to 1,000 operations total, failing atomically with BatchJobError.ASSET_GROUP_AND_ASSET_GROUP_ASSET_TRANSACTION_FAILURE; each AssetGroupOperation update or remove executes in a standalone single-operation sub-batch).
    • A Performance Max CampaignOperation (create, when Brand Guidelines are enabled—which is the default unless brand_guidelines_enabled is set to false or hotel_property_asset_set is set) followed by contiguous CampaignAssetOperation (create) operations for the same Campaign ID (up to 1,000 operations total, failing atomically with BatchJobError.CAMPAIGN_AND_CAMPAIGN_ASSET_TRANSACTION_FAILURE).
    • Consecutive AssetGroupListingGroupFilterOperation (max 10,000, failing atomically with BatchJobError.ASSET_GROUP_LISTING_GROUP_FILTER_TRANSACTION_FAILURE) or AdGroupCriterionOperation (listing_group, max 20,000, failing atomically with CriterionError.LISTING_GROUP_ERROR_IN_ANOTHER_OPERATION) operations for the same parent (AssetGroup or AdGroup).

Retrieve mutable attributes from the response

If you set the response_content_type of your mutate request to MUTABLE_RESOURCE, the response contains the resource_name and the resource object populated with its mutable fields (as well as key system-populated fields on the returned resource, such as ExperimentArm.in_design_campaigns) for every supported object created or updated (not removed) by the request. For remove operations—or for resource types that don't support returning MUTABLE_RESOURCE—the response always returns only the resource_name. Use this feature to avoid sending an additional Search or SearchStream request after each mutate call.

If you don't set response_content_type, the Google Ads API defaults to RESOURCE_NAME_ONLY and returns only the resource_name of each mutated resource.

The following example demonstrates how to retrieve a mutable resource from a mutate call:

Java

private String createExperimentArms(
    GoogleAdsClient googleAdsClient, long customerId, long campaignId, String experiment) {
  List<ExperimentArmOperation> operations = new ArrayList<>();
  operations.add(
      ExperimentArmOperation.newBuilder()
          .setCreate(
              // The "control" arm references an already-existing campaign.
              ExperimentArm.newBuilder()
                  .setControl(true)
                  .addCampaigns(ResourceNames.campaign(customerId, campaignId))
                  .setExperiment(experiment)
                  .setName("control arm")
                  .setTrafficSplit(40)
                  .build())
          .build());
  operations.add(
      ExperimentArmOperation.newBuilder()
          .setCreate(
              // In standard campaign experiments, creating the treatment arm automatically
              // generates a draft campaign that you can modify before starting the experiment.
              ExperimentArm.newBuilder()
                  .setControl(false)
                  .setExperiment(experiment)
                  .setName("experiment arm")
                  .setTrafficSplit(60)
                  .build())
          .build());

  try (ExperimentArmServiceClient experimentArmServiceClient =
      googleAdsClient.getLatestVersion().createExperimentArmServiceClient()) {
    // Constructs the mutate request.
    MutateExperimentArmsRequest mutateRequest =
        MutateExperimentArmsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .addAllOperations(operations)
            // We want to fetch the draft campaign IDs from the treatment arm, so the easiest way
            // to do that is to have the response return the newly created entities.
            .setResponseContentType(ResponseContentType.MUTABLE_RESOURCE)
            .build();

    // Sends the mutate request.
    MutateExperimentArmsResponse response =
        experimentArmServiceClient.mutateExperimentArms(mutateRequest);

    // Results always return in the order that you specify them in the request. Since we created
    // the treatment arm last, it will be the last result.  If you don't remember which arm is the
    // treatment arm, you can always filter the query in the next section with
    // `experiment_arm.control = false`.
    MutateExperimentArmResult controlArmResult = response.getResults(0);
    MutateExperimentArmResult treatmentArmResult =
        response.getResults(response.getResultsCount() - 1);

    System.out.printf(
        "Created control arm with resource name '%s'%n", controlArmResult.getResourceName());
    System.out.printf(
        "Created treatment arm with resource name '%s'%n", treatmentArmResult.getResourceName());

    return treatmentArmResult.getExperimentArm().getInDesignCampaigns(0);
  }
}

      

C#

private static (MutateExperimentArmResult, MutateExperimentArmResult)
    CreateExperimentArms(GoogleAdsClient client, long customerId, long baseCampaignId,
        string experimentResourceName)
{
    // Get the ExperimentArmService.
    ExperimentArmServiceClient experimentService = client.GetService(
        Services.V25.ExperimentArmService);

    // Create the control arm. The control arm references an already-existing campaign.
    ExperimentArmOperation controlArmOperation = new ExperimentArmOperation()
    {
        Create = new ExperimentArm()
        {
            Control = true,
            Campaigns = {
                ResourceNames.Campaign(customerId, baseCampaignId)
            },
            Experiment = experimentResourceName,
            Name = "Control Arm",
            TrafficSplit = 40
        }
    };

    // Create the non-control arm.
    // In standard campaign experiments, creating the treatment arm automatically
    // generates a draft campaign that you can modify before starting the experiment.
    ExperimentArmOperation treatmentArmOperation = new ExperimentArmOperation()
    {
        Create = new ExperimentArm()
        {
            Control = false,
            Experiment = experimentResourceName,
            Name = "Experiment Arm",
            TrafficSplit = 60
        }
    };

    // We want to fetch the draft campaign IDs from the treatment arm, so the
    // easiest way to do that is to have the response return the newly created
    // entities.
    MutateExperimentArmsRequest request = new MutateExperimentArmsRequest
    {
        CustomerId = customerId.ToString(),
        Operations = { controlArmOperation, treatmentArmOperation },
        ResponseContentType = ResponseContentType.MutableResource
    };

    MutateExperimentArmsResponse response = experimentService.MutateExperimentArms(
        request
    );

    // Results always return in the order that you specify them in the request.
    // Since we created the treatment arm last, it will be the last result.
    MutateExperimentArmResult controlArm = response.Results.First();
    MutateExperimentArmResult treatmentArm = response.Results.Last();

    Console.WriteLine($"Created control arm with resource name " +
        $"'{controlArm.ResourceName}'.");
    Console.WriteLine($"Created treatment arm with resource name" +
      $" '{treatmentArm.ResourceName}'.");
    return (controlArm, treatmentArm);
}
      

PHP

private static function createExperimentArms(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $campaignId,
    string $experimentResourceName
): string {
    $operations = [];
    $experimentArm1 = new ExperimentArm(
        [
        // The "control" arm references an already-existing campaign.
        'control' => true,
        'campaigns' => [ResourceNames::forCampaign($customerId, $campaignId)],
        'experiment' => $experimentResourceName,
        'name' => 'control arm',
        'traffic_split' => 40
        ]
    );
    $operations[] = new ExperimentArmOperation(['create' => $experimentArm1]);
    $experimentArm2 = new ExperimentArm(
        [
        // The non-"control" arm, also called a "treatment" arm, will automatically
        // generate draft campaigns that you can modify before starting the
        // experiment.
        'control' => false,
        'experiment' => $experimentResourceName,
        'name' => 'experiment arm',
        'traffic_split' => 60
        ]
    );
    $operations[] = new ExperimentArmOperation(['create' => $experimentArm2]);

    // Issues a request to create the experiment arms.
    $experimentArmServiceClient = $googleAdsClient->getExperimentArmServiceClient();
    $response = $experimentArmServiceClient->mutateExperimentArms(
        MutateExperimentArmsRequest::build($customerId, $operations)
            // We want to fetch the draft campaign IDs from the treatment arm, so the easiest
            // way to do that is to have the response return the newly created entities.
            ->setResponseContentType(ResponseContentType::MUTABLE_RESOURCE)
    );
    // Results always return in the order that you specify them in the request.
    // Since we created the treatment arm last, it will be the last result.
    $controlArmResourceName = $response->getResults()[0]->getResourceName();
    $treatmentArm = $response->getResults()[count($operations) - 1];
    print "Created control arm with resource name '$controlArmResourceName'" . PHP_EOL;
    print "Created treatment arm with resource name '{$treatmentArm->getResourceName()}'"
        . PHP_EOL;

    return $treatmentArm->getExperimentArm()->getInDesignCampaigns()[0];
}
      

Python

def create_experiment_arms(
    client: GoogleAdsClient,
    customer_id: str,
    base_campaign_id: str,
    experiment: str,
) -> str:
    """Creates a control and treatment experiment arms.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        base_campaign_id: the campaign ID to associate with the control arm of
          the experiment.
        experiment: the resource name for an experiment.

    Returns:
        the resource name for the new treatment experiment arm.
    """
    operations: List[ExperimentArmOperation] = []

    campaign_service: CampaignServiceClient = client.get_service(
        "CampaignService"
    )

    # The "control" arm references an already-existing campaign.
    operation_1: ExperimentArmOperation = client.get_type(
        "ExperimentArmOperation"
    )
    exa_1: ExperimentArm = operation_1.create
    exa_1.control = True
    exa_1.campaigns.append(
        campaign_service.campaign_path(customer_id, base_campaign_id)
    )
    exa_1.experiment = experiment
    exa_1.name = "control arm"
    exa_1.traffic_split = 40
    operations.append(operation_1)

    # In standard campaign experiments, creating the treatment arm automatically
    # generates a draft campaign that you can modify before starting the experiment.
    operation_2: ExperimentArmOperation = client.get_type(
        "ExperimentArmOperation"
    )
    exa_2: ExperimentArm = operation_2.create
    exa_2.control = False
    exa_2.experiment = experiment
    exa_2.name = "experiment arm"
    exa_2.traffic_split = 60
    operations.append(operation_2)

    experiment_arm_service: ExperimentArmServiceClient = client.get_service(
        "ExperimentArmService"
    )
    request: MutateExperimentArmsRequest = client.get_type(
        "MutateExperimentArmsRequest"
    )
    request.customer_id = customer_id
    request.operations = operations
    # We want to fetch the draft campaign IDs from the treatment arm, so the
    # easiest way to do that is to have the response return the newly created
    # entities.
    request.response_content_type = (
        client.enums.ResponseContentTypeEnum.MUTABLE_RESOURCE
    )
    response: MutateExperimentArmsResponse = (
        experiment_arm_service.mutate_experiment_arms(request=request)
    )

    # Results always return in the order that you specify them in the request.
    # Since we created the treatment arm second, it will be the second result.
    control_arm_result: Any = response.results[0]
    treatment_arm_result: Any = response.results[1]

    print(
        f"Created control arm with resource name {control_arm_result.resource_name}"
    )
    print(
        f"Created treatment arm with resource name {treatment_arm_result.resource_name}"
    )

    return treatment_arm_result.experiment_arm.in_design_campaigns[0]
      

Ruby

def create_experiment_arms(client, customer_id, base_campaign_id, experiment)
  operations = []
  operations << client.operation.create_resource.experiment_arm do |ea|
    # The "control" arm references an already-existing campaign.
    ea.control = true
    ea.campaigns << client.path.campaign(customer_id, base_campaign_id)
    ea.experiment = experiment
    ea.name = 'control arm'
    ea.traffic_split = 40
  end
  operations << client.operation.create_resource.experiment_arm do |ea|
    # The non-"control" arm, also called a "treatment" arm, will automatically
    # generate draft campaigns that you can modify before starting the
    # experiment.
    ea.control = false
    ea.experiment = experiment
    ea.name = 'experiment arm'
    ea.traffic_split = 60
  end

  response = client.service.experiment_arm.mutate_experiment_arms(
    customer_id: customer_id,
    operations: operations,
    # We want to fetch the draft campaign IDs from the treatment arm, so the
    # easiest way to do that is to have the response return the newly created
    # entities.
    response_content_type: :MUTABLE_RESOURCE,
  )

  # Results always return in the order that you specify them in the request.
  # Since we created the treatment arm last, it will be the last result.
  control_arm_result = response.results.first
  treatment_arm_result = response.results.last

  puts "Created control arm with resource name #{control_arm_result.resource_name}."
  puts "Created treatment arm with resource name #{treatment_arm_result.resource_name}."

  treatment_arm_result.experiment_arm.in_design_campaigns.first
end
      

Perl

sub create_experiment_arms {
  my ($api_client, $customer_id, $base_campaign_id, $experiment) = @_;

  my $operations = [];
  push @$operations,
    Google::Ads::GoogleAds::V25::Services::ExperimentArmService::ExperimentArmOperation
    ->new({
      create => Google::Ads::GoogleAds::V25::Resources::ExperimentArm->new({
          # The "control" arm references an already-existing campaign.
          control   => "true",
          campaigns => [
            Google::Ads::GoogleAds::V25::Utils::ResourceNames::campaign(
              $customer_id, $base_campaign_id
            )
          ],
          experiment   => $experiment,
          name         => "control arm",
          trafficSplit => 40
        })});

  push @$operations,
    Google::Ads::GoogleAds::V25::Services::ExperimentArmService::ExperimentArmOperation
    ->new({
      create => Google::Ads::GoogleAds::V25::Resources::ExperimentArm->new({
          # The non-"control" arm, also called a "treatment" arm, will automatically
          # generate draft campaigns that you can modify before starting the
          # experiment.
          control      => "false",
          experiment   => $experiment,
          name         => "experiment arm",
          trafficSplit => 60
        })});

  my $response = $api_client->ExperimentArmService()->mutate({
    customerId => $customer_id,
    operations => $operations,
    # We want to fetch the draft campaign IDs from the treatment arm, so the
    # easiest way to do that is to have the response return the newly created
    # entities.
    responseContentType => MUTABLE_RESOURCE
  });

  # Results always return in the order that you specify them in the request.
  # Since we created the treatment arm last, it will be the last result.
  my $control_arm_result   = $response->{results}[0];
  my $treatment_arm_result = $response->{results}[1];

  printf "Created control arm with resource name '%s'.\n",
    $control_arm_result->{resourceName};
  printf "Created treatment arm with resource name '%s'.\n",
    $treatment_arm_result->{resourceName};
  return $treatment_arm_result->{experimentArm}{inDesignCampaigns}[0];
}
      

curl