Using Read Scale-Out for Performance

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Lesson: Using Read Scale-Out for Performance in Business Central

Introduction: The Challenge of High-Volume Data Access

In the world of modern enterprise resource planning (ERP), Business Central often sits at the heart of an ecosystem. As businesses grow, the number of integrations—connecting e-commerce platforms, mobile applications, reporting tools, and external data warehouses—tends to increase exponentially. Each of these integrations relies on the API layer to read data from the Business Central database. Under normal conditions, these read requests are handled by the primary database instance. However, when the volume of requests becomes significant, these read operations can compete with critical business processes like posting invoices, running batch jobs, or updating inventory levels.

This is where the concept of Read Scale-Out becomes essential. Read Scale-Out is a database architecture feature that allows you to offload read-only queries to a secondary, read-only replica of your database. By separating heavy read traffic from the primary write-intensive traffic, you can ensure that your core business operations remain responsive even when external systems are pulling large datasets. In this lesson, we will explore how to implement and leverage Read Scale-Out for Business Central integrations, why it matters for your system’s stability, and how to architect your API calls to make the most of this capability.

Not read yet

Understanding the Architecture of Read Scale-Out

To understand Read Scale-Out, we must first distinguish between the primary and secondary database roles. In a standard Business Central environment, the primary database handles both read and write operations. If an integration sends a request to fetch ten thousand customer records, the primary database must locate those records, lock rows as necessary, and return the data. If this happens while a warehouse worker is trying to ship orders, the system might experience latency as the database engine juggles these competing tasks.

Read Scale-Out introduces a secondary replica that is a near-real-time copy of the primary database. When you configure your API calls to use this replica, the query is routed away from the primary instance. This means that your heavy reporting or data synchronization tasks do not consume the same processing resources required for transactional integrity. It is important to note that this is an asynchronous process; the secondary replica is typically seconds behind the primary. Therefore, the data you retrieve is "eventually consistent," which is usually acceptable for reporting and synchronization tasks, but not for scenarios where you need to check the absolute latest balance of an account before a transaction.

Callout: Eventual Consistency vs. Strong Consistency Understanding the difference between these two states is vital for any developer. Strong consistency ensures that the data you read is the absolute latest version, which happens on the primary database. Eventual consistency acknowledges that the secondary replica might be slightly behind the primary (usually by a few seconds). For high-volume read operations, choosing eventual consistency via Read Scale-Out provides massive performance gains at the cost of tiny, often negligible, delays in data synchronization.

Not read yet

When Should You Use Read Scale-Out?

Not every integration requires Read Scale-Out. In fact, for simple, low-frequency requests, the overhead of managing read-only connections might outweigh the benefits. You should evaluate your integration strategy based on the following criteria:

  • Data Volume: If your integration regularly pulls large datasets (e.g., thousands of records at a time), Read Scale-Out is a strong candidate.
  • Query Complexity: Complex queries that involve multiple joins, aggregations, or heavy filtering are prime candidates for offloading.
  • Integration Frequency: Integrations that run continuously or trigger frequently throughout the day will benefit from the resource isolation provided by a replica.
  • Sensitivity to Latency: If your business process can tolerate data that is a few seconds old, the read-only replica is ideal. If you require real-time accuracy for every single read, you must stick to the primary database.

Tip: Monitoring Your Database Load Before implementing Read Scale-Out, use the Business Central Performance Toolkit or Azure SQL monitoring tools to determine if your read operations are actually causing performance degradation. If your primary database is already running at low CPU and I/O utilization, Read Scale-Out might be an unnecessary architectural complexity.

Not read yet

Configuring Read Scale-Out for Business Central APIs

Implementing Read Scale-Out in Business Central is not a matter of changing a single checkbox in the UI. Instead, it is an architectural decision that you implement through how you structure your API requests and, in some cases, how you configure your environment.

The Role of OData and Web Services

Business Central exposes data primarily through OData and REST APIs. By default, these services point to the primary database. When you enable Read Scale-Out, you are essentially telling the system that read-only requests can be served by the secondary replica. The system handles the routing automatically based on the request type.

Step-by-Step Implementation Strategy

  1. Identify High-Impact Integrations: Start by auditing your current API integrations. Look for those that perform GET requests on large entities like SalesLines, LedgerEntries, or ItemLedgerEntries.
  2. Verify Data Consistency Requirements: Review the business requirements for these integrations. Confirm with stakeholders that data being a few seconds old is acceptable.
  3. Implement Read-Only Headers: When calling the API, ensure your requests are strictly read-only. This tells the platform that the request does not intend to modify data, allowing it to safely route the request to the secondary replica.
  4. Testing and Validation: Once configured, perform load tests using tools like Postman or custom scripts to compare response times between the primary database and the secondary replica.

Warning: Write Operations on Read-Only Replicas Never attempt to send a POST, PATCH, or DELETE request to an endpoint that is intended for read-only scaling. The system will reject these requests, and attempting to force them will lead to errors and potential data integrity issues. Always separate your write logic from your read logic.

Not read yet

Best Practices for API Integrations

To ensure your integrations are performant and reliable, you should follow these industry-standard practices. These rules apply whether you are using Read Scale-Out or the primary database.

  • Use Pagination: Never request an entire table. Always use $top and $skip parameters to retrieve data in manageable chunks. This reduces memory pressure on both the database and the API service.
  • Select Specific Fields: Use the $select parameter to pull only the fields you need. If you only need the No. and Name of a customer, do not request the entire record, which might include large blobs or dozens of unnecessary fields.
  • Filter Aggressively: Use the $filter parameter to limit the result set to exactly what you need. Filtering at the database level is significantly faster than filtering in your application code after the data has been transferred.
  • Implement Exponential Backoff: If your integration encounters a rate limit (HTTP 429), implement an exponential backoff strategy. Do not simply retry immediately, as this will further degrade performance.
  • Cache Locally: If the data you are reading changes infrequently, cache the results locally in your application or a temporary database. This avoids the need to call the API entirely for repeated data.

Not read yet

Comparing Read Operations: Primary vs. Secondary

The following table provides a quick reference to help you decide when to route traffic to the replica versus the primary database.

Feature Primary Database Secondary Replica (Read Scale-Out)
Consistency Strong (Real-time) Eventual (Seconds delay)
Operations Supported Read, Write, Update, Delete Read Only
Performance Impact High on transactional speed Low (offloads read traffic)
Best For Transactions, critical updates Heavy reporting, data sync, dashboards
Availability Always available Subject to replication lag

Common Pitfalls and How to Avoid Them

Even with a well-designed architecture, developers often run into issues when implementing Read Scale-Out. Here are the most common mistakes and how to steer clear of them.

Mistake 1: Assuming Real-Time Accuracy

A common error is designing an integration that relies on Read Scale-Out for a process that demands 100% real-time data. For example, if you are building an integration that checks if a customer has exceeded their credit limit before placing a web order, you cannot use the secondary replica. The delay in replication could mean that the replica shows the customer has credit available when, in reality, a transaction processed seconds ago on the primary database has already put them over the limit.

Mistake 2: Over-Engineering

Some developers implement Read Scale-Out for every single API call. This adds unnecessary complexity to the connection management and the infrastructure. If your integration is a simple lookup once every hour, the performance benefits will be negligible, and the cost of maintaining the connection logic may be higher than the benefit. Only apply this to high-traffic, high-volume scenarios.

Mistake 3: Ignoring Replication Lag

Replication lag is not always constant. During periods of high write activity on the primary database, the lag between the primary and the secondary replica can increase. If your application logic assumes a fixed replication delay (e.g., "I'll wait 500ms before reading"), you might find that your application fails or reads stale data when the network or database is under heavy load. Always design your application to be resilient to varying degrees of data freshness.

Mistake 4: Poor Query Optimization

Read Scale-Out is not a magic bullet for poorly written code. If your API call uses inefficient filters or requests too much data, it will perform poorly regardless of which database instance it hits. Always optimize your OData queries first, then apply Read Scale-Out as a scaling strategy.

Callout: The Importance of Query Optimization Before scaling out, perform a "query audit." Use the ?debug=1 parameter in your OData requests to see how the database is processing your query. Look for table scans versus index seeks. If you are doing a table scan, no amount of scaling will make your integration fast. Fix the query logic first by ensuring you are filtering on indexed fields.

Not read yet

Practical Code Implementation Example

Let's look at how you might structure a request in a C# application to fetch customer ledger entries. This example demonstrates how to implement pagination and filtering, which are critical for any performance-focused integration.

// Example: Fetching Customer Ledger Entries efficiently
public async Task<List<LedgerEntry>> GetRecentLedgerEntries(HttpClient client, DateTime sinceDate)
{
    // Always filter by date and use pagination
    string query = $"/api/v2.0/companies({companyId})/customerLedgerEntries" +
                   $"?$filter=postingDate ge {sinceDate:yyyy-MM-dd}" +
                   "&$select=id,customerNo,postingDate,amount" +
                   "&$top=1000";

    var response = await client.GetAsync(query);
    
    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<List<LedgerEntry>>(content);
    }
    
    throw new Exception("Failed to retrieve data.");
}

In the example above, we are selecting only the fields we need ($select), filtering by a date range ($filter), and limiting the response size ($top). When this request is executed against a system configured for Read Scale-Out, the API service recognizes this as a read-only request and routes it to the replica.

Not read yet

Advanced Configuration: Handling Large Datasets

When you need to sync very large amounts of data, such as a full historical sync of a ledger, even simple pagination can be slow. In these cases, you should consider using the ETag header or delta tokens if available.

Using Delta Queries

Delta queries allow you to request only the changes that have occurred since your last synchronization. This is the most efficient way to keep an external system in sync with Business Central. Instead of pulling the entire ledger, you only pull the records that were created or modified after a specific timestamp.

Parallel Processing

If you have massive datasets, you can perform multiple parallel requests to the replica. Because the replica is read-only, you don't need to worry about lock contention between your parallel threads. However, be mindful of the API rate limits of your Business Central environment.

// Parallel request example
var tasks = new List<Task<List<LedgerEntry>>>();
for (int i = 0; i < 5; i++)
{
    // Fetching different pages in parallel
    tasks.Add(FetchPage(client, i * 1000));
}
await Task.WhenAll(tasks);

Not read yet

Monitoring and Troubleshooting

Even with the best planning, things can go wrong. Monitoring is key to maintaining a high-performance integration.

  1. Log Latency: Always log the time it takes for an API call to complete. If you notice a spike in latency, check the Azure SQL database metrics to see if the secondary replica is under load or if there is a replication lag.
  2. Monitor Error Rates: Track the number of 4xx and 5xx errors. If you see an increase in 5xx errors, it might indicate that the secondary replica is unavailable or being refreshed.
  3. Use Telemetry: Use Application Insights to track your API calls. This will give you a clear picture of which endpoints are the slowest and where you should focus your optimization efforts.

Summary Checklist for Implementers

Before deploying your integration to production, run through this final checklist to ensure you have covered all the bases:

  • Query Optimization: Are you using $select and $filter to minimize the data payload?
  • Pagination: Is your integration designed to handle paginated results using $top and $skip?
  • Consistency Requirement: Have you confirmed that the integration can handle eventually consistent data?
  • Error Handling: Does your code handle HTTP 429 (Too Many Requests) with an exponential backoff?
  • Monitoring: Do you have telemetry in place to track response times and error rates?
  • Testing: Have you tested the integration against a sandbox environment that mimics your production data volume?

Not read yet

Key Takeaways

  1. Read Scale-Out is for Reads Only: This feature is strictly for offloading read-only traffic. Never attempt to perform write operations (POST/PATCH/DELETE) against a read-only replica.
  2. Consistency Trade-off: Understand that secondary replicas are eventually consistent. This is perfect for reporting and sync, but dangerous for real-time transactional checks.
  3. Efficiency First: Always optimize your OData queries with $select, $filter, and $top before relying on architectural scaling like Read Scale-Out.
  4. Resource Isolation: The primary benefit of Read Scale-Out is protecting your transactional performance from being impacted by heavy data-gathering tasks.
  5. Monitoring is Non-Negotiable: Use tools like Application Insights to monitor your API performance. Without data, you cannot know if your scaling efforts are actually successful.
  6. Design for Failure: Always build your integrations to handle transient errors and varying levels of database responsiveness.
  7. Right Tool for the Job: Not every integration needs Read Scale-Out. Use it only when the data volume or request frequency warrants the added complexity.

By following these principles, you can build Business Central integrations that are not only performant but also stable and capable of scaling alongside your business. Remember that the goal is to provide a smooth experience for the end-user while ensuring that your external systems receive the data they need in a timely and efficient manner. Always keep the balance between performance and data integrity at the forefront of your architectural decisions.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.