{"title":"Performance articles for developers","url":"https://jonas-paprotka.de/docs/dev-itpro/performance/performance-developer/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-developer, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-developer","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Learn how to write efficient AL code, pages, reports, and web services, and use tools like the AL Profiler to improve performance in Business Central.","date":"2026-09-18","meta":{"topic":"article"},"outline":[{"level":1,"title":"Performance articles for developers","slug":"performance-articles-for-developers","at":0,"chars":43680},{"level":2,"title":"Writing efficient pages","slug":"writing-efficient-pages","at":439,"chars":2675},{"level":3,"title":"Pattern - Avoid unnecessary recalculation","slug":"pattern---avoid-unnecessary-recalculation","at":646,"chars":835},{"level":3,"title":"Pattern - do less","slug":"pattern---do-less","at":1481,"chars":1009},{"level":3,"title":"Pattern - offloading the UI thread","slug":"pattern---offloading-the-ui-thread","at":2490,"chars":255},{"level":3,"title":"Making Edit-in-Excel faster","slug":"making-edit-in-excel-faster","at":2745,"chars":369},{"level":2,"title":"Writing efficient web services","slug":"writing-efficient-web-services","at":3114,"chars":6100},{"level":3,"title":"Endpoint performance","slug":"endpoint-performance","at":3415,"chars":3555},{"level":4,"title":"General anti-patterns (don't do this)","slug":"general-anti-patterns-dont-do-this","at":3440,"chars":2183},{"level":4,"title":"Performance patterns (do this)","slug":"performance-patterns-do-this","at":5623,"chars":1347},{"level":3,"title":"API/OData client performance patterns","slug":"apiodata-client-performance-patterns","at":6970,"chars":443},{"level":3,"title":"How to handle large throughput of web service calls","slug":"how-to-handle-large-throughput-of-web-service-calls","at":7413,"chars":1801},{"level":2,"title":"Performance patterns for business intelligence and reporting","slug":"performance-patterns-for-business-intelligence-and-reporting","at":9214,"chars":7296},{"level":3,"title":"Writing efficient AL reports","slug":"writing-efficient-al-reports","at":9278,"chars":2001},{"level":3,"title":"Stop using report properties DefaultLayout, ExcelLayout, RDLLayout, and WordLayout","slug":"stop-using-report-properties-defaultlayout-excellayout-rdllayout-and-wordlayout","at":11279,"chars":868},{"level":3,"title":"Loading data efficiently to Power BI","slug":"loading-data-efficiently-to-power-bi","at":12147,"chars":3465},{"level":3,"title":"Efficient extracts to data lakes or data warehouses","slug":"efficient-extracts-to-data-lakes-or-data-warehouses","at":15612,"chars":898},{"level":2,"title":"AL performance patterns","slug":"al-performance-patterns","at":16510,"chars":15029},{"level":3,"title":"Pattern - Use built-in data structures","slug":"pattern---use-built-in-data-structures","at":16884,"chars":1690},{"level":3,"title":"Pattern - Run async (and parallelize)","slug":"pattern---run-async-and-parallelize","at":18574,"chars":2372},{"level":3,"title":"Pattern - Use set-based methods instead of looping","slug":"pattern---use-set-based-methods-instead-of-looping","at":20946,"chars":1876},{"level":3,"title":"Pattern - Use partial records when looping over data, in reports, or when table extension fields aren't needed","slug":"pattern---use-partial-records-when-looping-over-data-in-reports-or-when-table-extension-fields-arent-needed","at":22822,"chars":1345},{"level":3,"title":"Table extension impact on performance (for Business Central 2023 release wave 1 and earlier)","slug":"table-extension-impact-on-performance-for-business-central-2023-release-wave-1-and-earlier","at":24167,"chars":2023},{"level":3,"title":"Limit your event subscriptions","slug":"limit-your-event-subscriptions","at":26190,"chars":751},{"level":3,"title":"Outgoing web service calls block AL execution","slug":"outgoing-web-service-calls-block-al-execution","at":26941,"chars":1212},{"level":3,"title":"Limit work done in sign in event subscribers","slug":"limit-work-done-in-sign-in-event-subscribers","at":28153,"chars":3386},{"level":2,"title":"Efficient data access","slug":"efficient-data-access","at":31539,"chars":8742},{"level":3,"title":"Tables and keys","slug":"tables-and-keys","at":31759,"chars":820},{"level":3,"title":"Using data audit fields to only read recent data","slug":"using-data-audit-fields-to-only-read-recent-data","at":32579,"chars":356},{"level":3,"title":"Nonclustered columnstore indexes (NCCI)","slug":"nonclustered-columnstore-indexes-ncci","at":32935,"chars":693},{"level":3,"title":"SumIndexField Technology (SIFT)","slug":"sumindexfield-technology-sift","at":33628,"chars":873},{"level":3,"title":"Set up the environment to calculate visible FlowFields only on pages","slug":"set-up-the-environment-to-calculate-visible-flowfields-only-on-pages","at":34501,"chars":713},{"level":3,"title":"How AL relates to SQL","slug":"how-al-relates-to-sql","at":35214,"chars":541},{"level":3,"title":"How to get insights into how AL translates to SQL","slug":"how-to-get-insights-into-how-al-translates-to-sql","at":35755,"chars":438},{"level":3,"title":"How to reduce database locking","slug":"how-to-reduce-database-locking","at":36193,"chars":3237},{"level":4,"title":"Database locking caused by web service calls","slug":"database-locking-caused-by-web-service-calls","at":37800,"chars":403},{"level":4,"title":"Non-blocking number sequences","slug":"non-blocking-number-sequences","at":38203,"chars":333},{"level":4,"title":"Analyzing database locks","slug":"analyzing-database-locks","at":38536,"chars":894},{"level":3,"title":"Using Read Scale-Out","slug":"using-read-scale-out","at":39430,"chars":851},{"level":2,"title":"Testing and validating performance","slug":"testing-and-validating-performance","at":40281,"chars":2651},{"level":3,"title":"Performance unit testing","slug":"performance-unit-testing","at":40565,"chars":329},{"level":3,"title":"Performance scenario and regression testing","slug":"performance-scenario-and-regression-testing","at":40894,"chars":688},{"level":3,"title":"Performance throughput analysis","slug":"performance-throughput-analysis","at":41582,"chars":556},{"level":3,"title":"Performance telemetry","slug":"performance-telemetry","at":42138,"chars":389},{"level":3,"title":"Troubleshooting","slug":"troubleshooting","at":42527,"chars":405},{"level":2,"title":"Tuning the development environment","slug":"tuning-the-development-environment","at":42932,"chars":345},{"level":2,"title":"Related information","slug":"related-information","at":43277,"chars":403}],"text":"# Performance articles for developers\nIn this article, you can read about ways to tune performance when developing for Business Central.\n #writing-efficient-pages\n #writing-efficient-web-services\n #writing-efficient-al-reports\n #al-performance-patterns\n #efficient-data-access\n #testing-and-validating-performance\n #tuning-the-development-environment\n Using the AL Profiler to analyze performance<../developer/devenv-al-profiler-overview>\n## Writing efficient pages\nThere are many patterns that a developer can use to get a page to load faster. Consider the following patterns:\n Avoid unnecessary recalculation\n Do less\n Offloading the UI thread\n### Pattern - Avoid unnecessary recalculation\nTo avoid unnecessary recalculation of expensive results, consider caching the data and refresh the cache regularly. Let's say you want to show the top five open sales orders or a VIP customers list on the role center. The content of such a list probably doesn't change significantly every hour. There's no need to calculate that from raw data every time the page is loaded. Instead, create a table that can contain the calculated data and refresh every hour/day using a background job.\nAnother example of unexpected recalculation is when using query objects. In contrast to using the record API, query results aren't cached in the primary key cache in the Business Central server. Any use of a query object always goes to the database. So, sometimes it's faster to not use a query object.\n### Pattern - do less\nOne way to speed up things is to reduce the amount of work that the system must do. For example, to reduce slowness of role centers, consider how many page parts are needed for the user. Another benefit of a simple page with few UI elements can also be ease of use and navigation.\nRemove calculated fields from lists if they aren't needed, especially on larger tables. Setting the field's Enabled or Visible properties to false isn't enough. The field definition needs to be removed from the page or page extension definition. Also, if indexing is inadequate, calculated fields can significantly slow down a list page.\nConsider creating dedicated lookup pages instead of the normal pages when adding a lookup (the one that looks like a dropdown) from a field. Default list pages run all triggers and fact boxes even if they aren't shown in the lookup. For example, Business Central 2019 release wave 1 added dedicated lookup pages for Customer, Vendor, and Item to the Base Application.\n### Pattern - offloading the UI thread\nTo get to a responsive UI fast, consider using Page Background Tasks for calculated values, for example, the values shown in cues.\nLearn more about Page Background Tasks in ../developer/devenv-page-background-tasks.\n### Making Edit-in-Excel faster\nThe Edit in Excel feature uses UI pages exposed through OData, which means that triggers need to be run for all records returned from the Business Central server to Excel. As a developer, you need to make your AL code conditional on the ClientType. Specifically, avoid updating fact boxes, avoid calculation, and avoid defaulting logic.\n## Writing efficient web services\nBusiness Central supports for web services to make it easier to integrate with external systems. As a developer, you need to think about performance of web services both seen from the Business Central server (the endpoint) and as seen from the consumer (the client).\n### Endpoint performance\n#### General anti-patterns (don't do this)\n Avoid using standard UI pages to expose as web service endpoints. Many things, such as fact boxes aren't returned in web service results, but use resources to prepare. Things that have historically caused performance issues on pages that are exposed as endpoints are:\n   Heavy logic in OnAfterGetCurrRecord or OnAfterGetRecord\n   Many SIFT fields\n   FactBoxes\n Avoid exposing calculated fields, because calculated fields are expensive. Try to move them to a separate page or to refactor the code so the value is stored on the physical table (if applicable). Complex types are also a performance hit because they take time to calculate.\n Don't use temp tables as a source if you have many records. Temp tables that are based on APIs are a performance hit. The server has to fetch and insert every record, and there's no caching on data in temp tables. Paging becomes difficult to do in a performant manner. A rule of thumb is if you have more than 100 records, don't use temp tables.\n Don't insert child records belonging to same parent in parallel. This condition causes locks on parent and Integration Record tables because parallel calls try to update the same parent record. The solution is to wait for the first call to finish or use $batch, which will make sure calls get executed one after another.\n Don't use a deprecated protocol such as SOAP. Instead, utilize newer technology stacks such as OData, or preferably API pages/queries. The latter are up to 10 times faster than using the SOAP protocol.\nIf you're migrating a SOAP integration that calls codeunit procedures, consider OData V4 unbound actions for supported procedure signatures. See Create and call an OData V4 unbound action<../developer/devenv-creating-and-interacting-with-odatav4-unbound-action>.\nWhen reading data from API queries, the use of aggregation methods can affect performance. Don't define this method if you intend to read data on the highest granularity of the underlying table (for example, the entry no. on G/L Entries). While the method property is meaningful for aggregated data, it slows down the performance in context of detailed level queries.\n#### Performance patterns (do this)\n Instead of exposing UI pages as web service endpoints, use the API pages or API queries because they've been optimized for this scenario. Select the highest API version available. Don't use the beta version of the API pages. To read more about API pages, see API Page Type<../developer/devenv-api-pagetype>.\n If you do expose UI pages as web service endpoints, then triggers must be run for all records returned from the Business Central server. As a developer, you must make your AL code conditional on the ClientType. Specifically, avoid updating FactBoxes, avoid calculation, and avoid defaulting logic. See ../developer/methods-auto/system/system-guiallowed-method.\n The choice of protocol (SOAP, OData, or APIs) for the endpoint can significantly affect performance. Favor OData version 4 or APIs for the best performance. You can expose procedures in a codeunit as an OData endpoint by using unbound actions. See Create and call an OData V4 unbound action<../developer/devenv-creating-and-interacting-with-odatav4-unbound-action>.\n If you want OData endpoints that work as data readers (like for consumption in Power BI), consider using API queries and set `DataAccessIntent = ReadOnly`. See API Query Type<../developer/devenv-api-querytype> and ../developer/properties/devenv-dataaccessintent-property.\n### API/OData client performance patterns\nWhen calling APIs and OData web services, there are many strategies that you can use to speed up your queries, like:\n Limiting the set ($filter or $top) if you're using an expensive $expand statement\n Using OData transaction $batch\n Using Data Access Intent Read-only with OData\nFor more information about OData query performance, see OData Query Performance<../webservices/odata-client-performance>.\n### How to handle large throughput of web service calls\nWhen integrating to Business Central from external systems using web services, it's important to understand the operational limits for the Business Central servers that host the web service endpoints being called. To ensure that excessive traffic doesn't cause stability and performance issues for all users, the online version of Business Central server has set up throttling limits on web service endpoints.\nMake sure that your external application can handle the three HTTP status codes 429 (Too Many Requests), 503 (Service Temporarily Unavailable), and 504 (Gateway Timeout).\n Handling status codes 429 and 503 requires the client to adopt a retry logic while providing a cool off period. You can apply different strategies, like:\n   Regular interval retry\n   Incremental intervals retry\n   Exponential back-off\n   Randomization\n Handling status code 504 - Gateway Timeout requires the client to refactor the long running request to execute within time limit by splitting the request into multiple requests. Then, deal with potential 429 codes by applying a back off strategy.\nA common pattern is to implement a queue in your external application so that you can flatten spikes of traffic. If a request gets the HTTP status code 429 (Too Many Requests) or 503 (Service Temporarily Unavailable), then put it back in the queue and apply one of the retry strategies described previously.\nRead more about web service limits, see Working with API limits in Dynamics 365 Business Central<../api-reference/v2.0/dynamics-rate-limits>.\nThe same advice applies for outgoing web service calls using the AL module HttpClient. Make sure your AL code can handle slow response times, throttling, and failures in external services that you integrate with.\n## Performance patterns for business intelligence and reporting\n### Writing efficient AL reports\nReports generally fall into two categories. They can be specific to a single instance of an entity, like an invoice. Or, they can be of a more analytical nature that joins data from multiple instances of multiple entities. Typically, performance issues in reports lie in the latter category. The following articles contain advice about implementing faster reports:\n Use Read Scale-Out to read data from a read-only copy of the database, see Using Read Scale-Out for Better Performance<../administration/database-read-scale-out-overview> for more information.\n Use Partial Records to reduce the data loaded from the database, see Using Partial Records<../developer/devenv-partial-records> for more information.\n Use AL queries to optimize the way data is read from the database, see Queries in Business Central<../developer/devenv-query-overview> for more information.\n Compared to Word layouts, RDL layouts can result in slower performance with document reports, especially for actions related to the user interface (like sending emails). See Creating an RDL Layout Report<../developer/devenv-howto-rdl-report-layout>.\n Can you run the report in the background? It will not make it run faster, but the user might feel this way (as they are not blocked in the UI while waiting on the report to finish). See /ui-work-report#ScheduleReport.md.\n> TIP\n> From the Business Central client, you can export report results as raw data to a Microsoft Excel file. The file contains all columns of the dataset, but without the layout applied. Use the file to help validate that the report returns the expected data, and to ensure that the report layout controls match the dataset value types. To export a report dataset to Excel, run the report and select the Send to > Microsoft Excel Document (data only) on the request page. See /ui-work-report#send-to-excel.\nLearn more about how to use telemetry to analyze the performance of reports in ../developer/devenv-report-performance\n### Stop using report properties DefaultLayout, ExcelLayout, RDLLayout, and WordLayout\n> WARNING\n> Using the report properties DefaultLayout, ExcelLayout, RDLCLayout, and WordLayout should be avoided as these properties will be deprecated in a later release. Instead, it's recommended to use the property DefaultRenderingLayout together with the new rendering syntax introduced in runtime version 9.0.\n> In Visual Studio Code, when hovering over any line with the ExcelLayout, RDLLayout, or WordLayout property, you can use the code action Convert to 'Rendering' to convert to the new rendering syntax.\n> See ../developer/properties/devenv-defaultrenderinglayout-property.\n> The use of any of these report properties impact performance as every call loads the full layout in memory even if the intent is only to check if a given report had a layout of the given type.\n### Loading data efficiently to Power BI\nWhen calling APIs and OData web services from Power BI, it's important that you understand the concepts of query folding. The Business Central connector uses the https://learn.microsoft.com/powerquery-m/odata-feed library behind the scenes, which translates numerous the Power BI constructs into OData query parameters. For example:\n Table.RemoveColumns or Table.SelectColumns becomes $select\n Table.SelectRows becomes $filter\n Table.ExpandTableColumn becomes $expand\nThe following example illustrates how filters are pushed from Power BI to the Business Central connector.\nIt is common practice to have a query that refreshes the current date and time at every refresh in your Power BI dataset:\n```powerquery-m\n// LastRefreshDate query\nlet\n    Source = DateTimeZone.UtcNow()\nin\n    Source\n```\nTo apply a filter such as \"the last 12 months of data\" to other queries, simply use the PowerQuery _Table.SelectRows_ on appropriate dates, for example:\n```powerquery-m\n// SalesInvoices\n// Filtered to last 12 months\nlet\n    Source = Dynamics365BusinessCentral.ApiContentsWithOptions(null, null, null, null),\n    PRODUCTION = Source{[Name=\"PRODUCTION\"]}[Data],\n    #\"CRONUS USA, Inc.\" = PRODUCTION{[Name=\"CRONUS USA, Inc.\"]}[Data],\n    v2.0 = #\"CRONUS USA, Inc.\"{[Name=\"v2.0\"]}[Data],\n    salesInvoices_table = v2.0{[Name=\"salesInvoices\",Signature=\"table\"]}[Data],\n    filteredRows = Table.SelectRows(salesInvoices_table, each [postingDate] > Date.From(Date.AddMonths(LastRefreshDate, -12)))\nin\n    filteredRows\n```\nFor a LastRefreshDate of _2022-08-17_, the Power BI connector adds this `$filter` predicate to the API call:\n`/v2.0/PRODUCTION/api/v2.0/salesInvoices?$filter=postingDate gt 2022-08-17&company=CRONUS USA, Inc.`\nFor more information about query folding in Power BI, see https://learn.microsoft.com/power-query/power-query-folding.\n> NOTE\n> Query folding optimizations might not be applied in a few cases:\n > Query folding is NOT applied when loading data preview (such as while you are editing your query and data updates in the query editor screen).\n > Be careful if you do joins with other data in Power Query. If you do, some OData.Feed limitations might apply, and the OData parameters will be applied client side instead. The Workaround from the Power BI team is to use Table.Buffer before doing any join. For more information, refere to Known issues and limitations in OData-based Power BI connectors<https://learn.microsoft.com/power-query/connectors/odata-feed#joins>.\nFor more information about OData/API client performance in Business Central, see OData query performance<../webservices/odata-client-performance>.\nWhen refreshing a query in a Power BI semantic model, you might experience an error such as `DataSource.Error: OData: Unable to read data from the transport connection: existing connection was forcibly closed by the remote host.` This error can happen either when the query refresh was interrupted by a transient error (in this case, just implement a retry) or if the query can't finish within the limit defined for web service calls on the Business Central server. In the latter case, the Business Central server will cancel the call. If this happens consistently, you need to tune your query, either by applying data filters, by reducing the number of columns (do you use all of them?), or maybe by partitioning the table (using custom partitioning through the XMLA endpoint for the model).\n### Efficient extracts to data lakes or data warehouses\nWhen establishing a data lake or a data warehouse, you typically need to do two types of data extraction:\n1. A historical load (all data from a given point-in-time)\n2. Delta loads (what's changed since the historical load)\nThe fastest (and least disruptive) way to get a historical load from Business Central online is to get a database export as a BACPAC file (using the Business Central admin center) and restore it in Azure SQL Database or on a SQL Server. For on-premises installations, you can just take a backup of the tenant database.\nThe fastest and least disruptive way to get delta loads from Business Central online is to set up API queries configured with Read Scale-Out and use the data audit field LastModifiedOn (introduced in version 17.0) on filters.\nSee Extract data from Business Central<../developer/devenv-extract-data>.\n## AL performance patterns\nKnowledge about different AL performance patterns can greatly improve the performance of the code you write. In this section, we describe the following patterns and their impact on performance.\n Use built-in data structures<#builtindatastructure>\n Run async (and parallelize)<#runasync>\n Use set-based methods instead of looping<#setbasedmethods>\n### Pattern - Use built-in data structures\nAL comes with built-in data structures that have been optimized for performance and server resource consumption. Make sure that you're familiar with them to make your AL code as efficient as possible.\nWhen working with strings, make sure to use the TextBuilder data type, and not repeated use of the `+=` operator on a Text variable. General guidance is to use a Text data type if you concatenate fewer than five strings (here the internal allocation of a TextBuilder and the final ToText invocation is more expensive). If you need to concatenate five strings or more or concatenate strings in a loop, then TextBuilder is faster. Also, use a TextBuilder data type instead of BigText when possible. See ../developer/methods-auto/textbuilder/textbuilder-data-type.\nIf you need a key-value data structure that is optimized for fast lookups, use a Dictionary data type. See ../developer/methods-auto/dictionary/dictionary-data-type.\nUse a List data type if you need an unbound \"array\" (where you would previously create a temporary table object). See ../developer/methods-auto/list/list-data-type.\nUse the Media or Mediaset data types instead of the Blob data type. The Media and MediaSet data types have a couple advantages over the Blob data type when working with images. First of all, a thumbnail version of the image is generated when you save the data. You can use the thumbnail when loading a page and then load the larger image asynchronously using a page background task. Second, data for Media and MediaSet data types is cached on the client. Data for the Blob data type is never cached on the server. It's always fetched from the database.\n### Pattern - Run async (and parallelize)\nUse asynchronous processing to run AL code without making users wait for a batch to finish. You can also split independent work into smaller tasks and run them in parallel.\nChoose a mechanism based on the work you need to run and its lifetime. The following table also identifies the main Business Central online limits.\nMechanism|Characteristics|Main Business Central online limits\n../developer/devenv-page-background-tasks|Read-only database access in a child session tied to the calling page and parent session. Canceled if the page or parent session closes, the current record changes, or the task times out. Can also be canceled explicitly.|Child session concurrency and queue length; page background task timeouts<../administration/operational-limits-online#Task>\n../developer/methods-auto/session/session-startsession-integer-integer-string-table-method|Creates a background session on the same Business Central Server instance when called. Codeunit execution can wait in the background-session queue. Not tied to a page or the lifetime of the calling session. Can write to the database, subject to permissions. Subject to background-session queueing and timeout controls.|Background session concurrency, queue length, and waiting timeout<../administration/operational-limits-online#Task>\n../developer/devenv-task-scheduler|Stores a task for execution when it's ready and its earliest start time has passed. Runs in a background session on an eligible server instance in the cluster. Tasks are persisted in the database and recoverable after server restarts. Monitor execution through task scheduler telemetry and session events.|Scheduled task concurrency<../administration/operational-limits-online#TaskUser>\n../developer/devenv-job-queue|Supports one-time and recurring schedules. Uses the task scheduler to run in a background session on an eligible server instance. Uses persisted job queue entries and scheduled tasks, with restart recovery. Records execution status and error details in Job Queue Log Entries.|Scheduled task concurrency, shared with other scheduled tasks<../administration/operational-limits-online#TaskUser>\nFor scheduled tasks, the server instance must have task scheduling enabled and serve the tenant. Restart recovery can rerun work; it doesn't resume execution at the interrupted instruction.\n### Pattern - Use set-based methods instead of looping\nThe AL methods such as FindSet, CalcFields, CalcSums, and SetAutoCalcFields are examples of set-based operations that are faster than looping over a result set and do the calculation for each row.\n CalcFields, CalcSums, and Count<../administration/optimize-sql-al-database-methods-and-performance-on-server#calc>\n ../developer/methods-auto/recordref/recordref-findset-boolean-method\nOne common use of the CalcSums method is to efficiently calculate totals.\nTry to minimize work done in the OnAfterGetRecord trigger code. Common performance coding patterns in this trigger are:\n Avoiding CalcFields calls. Defer them until the end.\n Avoiding `CurrPage.Update()` calls.\n Avoiding repeated calculations. Move them outside the loop, if possible.\n Avoid changing filters. This pattern requires the server to throw away the result set.\n Never do any database writes here. With more than one user on the system, this gives database locking issues and even deadlock errors.\nConsider using a query object if you want to use a set-based coding paradigm. These pros and cons for using query objects:\nPros for using a query object|Cons for using a query object\n- Bypasses the AL record API where server reads all fields. <br> - With a covering index, you can get fast read performance for tables with many fields. <br> - Can join multiple tables.|- Query object result sets aren't cached in the server's primary key (data) cache. <br> - No writes are allowed. <br> - You can't add a page on a query object.\nRead more about query objects here:\n Using queries instead of record variables<../developer/devenv-query-using-instead-record-variables>\n ../developer/devenv-query-object\n ../developer/devenv-query-overview\n ../developer/properties/devenv-topnumberofrows-property\n ../administration/optimize-sql-query-objects-and-performance\n### Pattern - Use partial records when looping over data, in reports, or when table extension fields aren't needed\nWhen writing AL code for which the fields needed on a record or recordref are known, you can use the partial records capability to only load out these fields initially. The remaining fields are still accessible, but they'll be loaded as needed.\nPartial records improve performance in two major ways. First, they limit the fields that need to be loaded from the database. Loading more fields leads to more data being read, sent over the connection, and created on the record. Second, partial records limit the number of table extensions that need to be joined.\n> NOTE\n> With Business Central 2023 release wave 2, the data model for table extensions has changed. In this new model, data from all table extensions on a table are stored in the same companion table. This means that there will be at most one SQL join involved when doing data operations on the table (as seen from AL). Partial records can still eliminate the join to the single companion table in Business Central 2023 release wave 2, if all loaded fields reside in the base table.\nThe performance gains compound when looping over many records, because both effects scale with the number of rows loaded.\nSee Using Partial Records<../developer/devenv-partial-records>.\n### Table extension impact on performance (for Business Central 2023 release wave 1 and earlier)\n> NOTE\n> In version 23, the data model for table extensions was changed. In this new model, data from all table extensions on a table are stored in the same companion table. This means that there will be at most one SQL join involved when doing data operations on the table (as seen from AL).\nTable extensions are separate tables in the database and therefore need to be joined together in the data stack when accessed via a record. With tables extensions being stored individually, the amount of joins necessary grows with the number of table extensions extending a table. Together with the current inability to define indexes that span base and extension fields, one should avoid splitting one's code into too many table extensions.\nWith central tables to the application, such as General Ledger Entry (G/L Entry), one should be extra cautious adding table extensions since these tables are frequently used throughout the application.\nThe adverse affects of many table extensions can be mitigated with the application of partial records, learn more in Using partial records<../developer/devenv-partial-records>. However, since the developer may not have ownership of all executed code, and therefore isn't able to apply partial records everywhere, the above recommendation still stands.\nAn alternative approach when doing data modeling for extending a table with new fields is to use a related table and define a FlowField on the base table.\nHere are the pros and cons of the two data models:\nData model for extending a table|Properties\nTable extension|Fields can be added to lists and are searchable. <br> Always loaded with the base table. <br> Expensive at runtime but easy to use. <br> Use only for critical fields.\nRelated tables|Need to set up table relations. <br> Dedicated page for editing. <br> Requires flow field to be shown in lists. <br> Doesn't affect performance of base table. <br> Excellent for FactBoxes.\n### Limit your event subscriptions\nThe following are best practices for getting performant events:\n There's no significant cost of having a publisher defined.\n Static automatic has a cost over manually binding (there's an overhead of creating and disposing objects).\n Codeunit size of the subscriber matters. Try to have smaller codeunits.\n Use single instance codeunits for subscribers, if possible.\nTable events change the behavior of SQL optimizations on the Business Central Server in the following ways:\n The Business Central Server will issue SQL update/delete statements row in a for loop rather than one SQL statement.\n They impact ModifyAll and DeleteAll methods that normally do bulk SQL operations to be forced to do single row operations.\n### Outgoing web service calls block AL execution\nIf you call an external web service using the HttpClient module in AL, be aware that the Business Central Server blocks the execution of AL code for the session until the call completes. For interactive sessions, this behavior means that the user sees a spinning wheel during the call.\nIf you have enabled telemetry for your environment or app, you can use this KQL query to analyze how much time users are delayed in the UI by calls to external services.\n```kusto\ntraces\n| where customDimensions has 'RT0019'\n| where customDimensions.clientType == 'WebClient'\n| extend executionTimeInMs = toreal(totimespan(customDimensions.serverExecutionTime))/10000 //the datatype for executionTime is timespan\n| summarize count() // how many calls\n, sum(executionTimeInMs) // sum of delays for UI sessions\n, avg(executionTimeInMs) // average waiting time by this app\n, max(executionTimeInMs) // average waiting time by this app\nby\n// which app is calling out from the UI\n  extensionPublisher = tostring( customDimensions.extensionPublisher )\n, extensionName = tostring( customDimensions.extensionName )\n, extensionVersion = tostring( customDimensions.extensionVersion )\n```\n### Limit work done in sign in event subscribers\nThe events _OnCompanyOpen_ and _OnCompanyOpenCompleted_ are raised every time a session is created. Only when the code for all event subscribers on these events has completed can the session start running AL code. Until code has completed, the session creation process will wait. For interactive sessions, the user will see a spinner. Web service calls (SOAP, OData, or API) or background sessions (job queue, scheduled tasks, page background tasks) will not start running.\nThis behavior means that you must design such code in a way that is minimally intrusive, for example, set low timeouts for outgoing web service calls.\nOne or more of these operations typically are involved in a performance issue on logins:\n1. Calls to external services\n2. Long running SQL calls to the database\nIf you have enabled telemetry for your environment or app, you can use this KQL query to analyze how session creation time is delayed by calls to external services.\n```kusto\ntraces\n| where timestamp > ago(1d) // adjust as needed\n| where customDimensions.eventId == 'RT0019'\n| where isnotempty( customDimensions.alStackTrace ) // RT0019 only has stacktrace from 20.1\n| extend StackTrace = tostring( customDimensions.alStackTrace )\n, executionTimeInMs = toreal(totimespan(customDimensions.serverExecutionTime))/10000 //the datatype for executionTime is timespan\n| where StackTrace has 'OnCompanyOpen' or StackTrace has 'OnCompanyOpenCompleted'\n| summarize count() // how many calls\n, sum(executionTimeInMs) // sum of delays for session creations (all session types are affected: UI, web service, background, ...)\n, avg(executionTimeInMs) // average session creation time delay by this app\n, max(executionTimeInMs) // average session creation time delay by this app\nby\n// which app is calling out from OnCompanyOpen/OnCompanyOpenCompleted?\n  extensionId = tostring( customDimensions.extensionId )\n, extensionName = tostring( customDimensions.extensionName )\n, extensionVersion = tostring( customDimensions.extensionVersion )\n// session type: UI, web service, background, ...\n, clientType = tostring( customDimensions.clientType )\n```\nUse this KQL query to analyze how session creation time is delayed by calls to the database:\n```kusto\ntraces\n| where timestamp > ago(1d) // adjust as needed\n| where customDimensions.eventId == 'RT0005'\n| where isnotempty( customDimensions.alStackTrace ) // RT0019 only has stacktrace from 20.1\n| extend StackTrace = tostring( customDimensions.alStackTrace )\n, executionTimeInMs = toreal(totimespan(customDimensions.executionTime))/10000 //the datatype for executionTime is timespan\n| where StackTrace has 'OnCompanyOpen' or StackTrace has 'OnCompanyOpenCompleted'\n| summarize count() // how many calls\n, sum(executionTimeInMs) // sum of delays for session creations (all session types are affected: UI, web service, background, ...)\n, avg(executionTimeInMs) // average session creation time delay by this app\n, max(executionTimeInMs) // average session creation time delay by this app\nby\n// which app is querying the database\n  extensionId = tostring( customDimensions.extensionId )\n, extensionName = tostring( customDimensions.extensionName )\n, extensionVersion = tostring( customDimensions.extensionVersion )\n// session type: UI, web service, background, ...\n, clientType = tostring( customDimensions.clientType )\n```\n## Efficient data access\nMany performance issues are related to how data is defined, accessed, and modified. It's important to know how concepts in AL metadata and the AL language translate to their counterparts in SQL.\n### Tables and keys\nMany performance issues can be traced back to missing indexes (also called keys in Business Central), but index design is often not a key skill for AL developers. For best performance, even with large amounts of data, it's imperative to design appropriate indexes according to the way your code accesses data.\nThese articles on indexing are worth knowing as an AL developer:\n About table keys<../developer/devenv-table-keys>\n Table keys and performance in Business Central<../administration/optimize-sql-table-keys-and-performance>\n About SQL Server indexes<https://learn.microsoft.com/sql/relational-databases/indexes/clustered-and-nonclustered-indexes-described>\n ../administration/database-missing-indexes\nIndexes have a cost to update, so it's recommended to not add too many of them on a table.\n### Using data audit fields to only read recent data\nEvery table in Business Central includes the following two system fields, which you can use to filter records:\n SystemCreatedAt\n SystemModifiedAt\nOne example is to use the system field SystemModifiedAt to implement delta reads. Learn more about system fields in ../developer/devenv-table-system-fields.\n### Nonclustered columnstore indexes (NCCI)\nStarting in the 2021 release wave 2 of Business Central, non-clustered columnstore indexes (sometimes referred to as NCCIs) are supported on tables.\nYou can use a non-clustered columnstore index to efficiently run real-time operational analytics on the Business Central database without the need to define SIFT indexes up front (and without the locking issues that SIFT indexes sometimes impose on the system.)\nRead more about non-clustered columnstore indexes here:\n ColumnStoreIndex table property<../developer/properties/devenv-columnstoreindex-property>\n https://learn.microsoft.com/sql/relational-databases/indexes/columnstore-indexes-overview\n### SumIndexField Technology (SIFT)\nSumIndexField Technology (SIFT) lets you quickly calculate the sums of numeric data type columns in tables, even in tables with thousands of records. The data type includes Decimal, Integer, BigInteger, and Duration. SIFT optimizes the performance of FlowFields and query results in a Business Central application.\nEnsure appropriate SIFT indices for all FlowFields of type sum or count.\nRead more about SIFT here:\n SumIndexField Technology (SIFT)<../developer/devenv-sift-technology>\n ../developer/devenv-sift-performance\n ../developer/devenv-sift-tuning-and-tracing\n ../developer/devenv-sift-and-sql-server\nLearn how to find missing SIFT indexes on FlowFields in Troubleshooting: Long Running SQL Queries Involving FlowFields by Disabling SmartSQL<../administration/troubleshooting-queries-involving-flowfields-by-disabling-smartsql>.\n### Set up the environment to calculate visible FlowFields only on pages\nWhen you add a FlowField to a page or page extension with the ../developer/properties/devenv-visible-property set to false, the FlowField doesn't appear on the page. However, its value is still calculated, leading to unnecessary computations and performance issues. As an admin, you can change this behavior by enabling the Calculate only visible FlowFields feature in the Feature Management page. When enabled, the AL runtime calculates values only for FlowFields that are visible on pages.\nSee FlowFields overview<../developer/devenv-flowfields> and Enabling upcoming features in Feature Management<../administration/feature-management>.\n### How AL relates to SQL\nThe AL programming language, to some degree, hides how data is read and written to the database. To effectively code for performance, you need to know how AL statements translate to the equivalent SQL statements.\nThe following articles cover how AL relates to SQL:\n ../administration/optimize-sql-al-database-methods-and-performance-on-server\n ../administration/optimize-sql-data-access\n Data read/write performance<../administration/optimize-sql-data-access#readwrite>\n ../administration/optimize-sql-bulk-inserts\n### How to get insights into how AL translates to SQL\nIf you want to track how Business Central Server translates AL statements to SQL statements, use either database statistics in the AL debugger or telemetry on long running queries.\nRead more here:\n About database statistics in the AL debugger<../developer/devenv-debugging#DebugSQL>\n Telemetry on long running SQL queries<../administration/monitor-long-running-sql-queries-event-log>\n### How to reduce database locking\nSometimes, performance issues aren't due to resource starvation, but due to processes waiting for other processes to release locks on shared objects. When AL code needs to update data, it's customary to take a database lock on it to ensure that other processes don't change the data at the same time.\nUsing the Record.LockTable method applies the `WITH (updlock)` hint on all subsequent read calls to the database against the table of the record called on, until the transaction is committed. For example, if Record.LockTable is called on an Item record, all reads against that table will be done with the UPDLOCK hint, not just the variable it was called on. Hence, it's good practice to defer the Record.LockTable call as late as possible in your AL code, to make sure that only the data that is in scope for being updated, is locked. See ../developer/methods-auto/record/record-locktable-method\nSome tips for avoiding locking:\n Enable ../developer/devenv-tri-state-locking to avoid reads-after-writes taking locks.\n Read setup information before starting write transactions\n If possible, limit the time, you hold locks\n If possible, limit transaction size (divide into smaller operations that can be committed)\n Make sure you have indexes on ranges you update\n Locking is much less of an issue if you have a logical separation across companies\n Set record instance isolation level on transactions to isolate them from other transactions to prevent problems in concurrent situations. Learn more about record instance isolation level<../developer/devenv-read-isolation>.\n#### Database locking caused by web service calls\nDon't insert child records belonging to the same parent record in parallel. This condition causes locks on both the parent table and the integration record table because parallel calls try to update the same parent record. The solution is to wait for the first call to finish or use OData `$batch`, which will make sure calls get run one after another.\n#### Non-blocking number sequences\nIf you need a fast, non-blocking number sequence that can be used from AL, refer to the number sequence object type. Use a number sequence object if you:\n Don't want to use a number series\n Can accept holes in the number range\nSee ../developer/methods-auto/numbersequence/numbersequence-data-type.\n#### Analyzing database locks\nThere are two tools that you can use to analyze database locks happening in the environment: the Database Locks page, and database lock time-out telemetry.\nThe Database Locks page gives a snapshot of all current database locks in SQL Server. It provides information like the table and database resource affected by the lock, and sometimes also the AL object or method that ran the transaction that caused the lock. These details can help you better understand the locking condition.\nDatabase lock timeout telemetry gathers information about database locks that have timed out. The telemetry data allows you to troubleshoot what caused these locks.\nRead more here:\n /admin-view-database-locks\n Monitoring SQL Database Locks<../administration/monitor-database-locks>\n Analyzing Database Lock Timeout Trace Telemetry<../administration/telemetry-database-locks-trace>\n### Using Read Scale-Out\nBusiness Central supports the Read Scale-Out feature in Azure SQL Database and SQL Server. Read Scale-Out is used to load-balance analytical workloads in the database that only read data. Read Scale-Out is built in as part of Business Central online, but it can also be enabled for on-premises.\nRead Scale-Out applies to queries, reports, or API pages. With these objects, instead of sharing the primary, set them up to run against a read-only replica. This setup isolates them from the main read-write workload so they don't affect the performance of business processes.\nAs a developer, you control Read Scale-Out on report, API page, and query objects by using the ../developer/properties/devenv-dataaccessintent-property. See Using Read Scale-Out for Better Performance<../administration/database-read-scale-out-overview>.\n## Testing and validating performance\nIt's imperative to test and validate a Business Central project before deploying it to production. In this section, you find resources on how to analyze and troubleshoot performance issues and guidance on how to validate performance of a system.\n### Performance unit testing\nYou can use the SessionInformation data type in unit tests that track the number of SQL statements or rows read. Use it before and after the code to be tested. Then, have assert statements that check for normal behavior.\nSee ../developer/methods-auto/sessioninformation/sessioninformation-data-type.\n### Performance scenario and regression testing\nUse the Performance Toolkit to simulate the amount of resources that customers use in realistic scenarios to compare performance between builds of their solutions.\nThe Performance Toolkit helps answer questions such as, \"Does my solution for Business Central support X number of users doing this, that, and the other thing at the same time?\"\nSee The Performance Toolkit Extension<../developer/devenv-performance-toolkit>.\n> NOTE\n> To test insert/update performance, make sure to un-install the test framework first. If the test framework is installed, then no insert/update statements can utilize bulk mode and will instead run row-by-row.\n### Performance throughput analysis\nThe Performance Toolkit doesn't answer questions such as, \"How many orders can Business Central process per hour?\" For this kind of analysis, test the time to execute key scenarios using the Performance Toolkit, and then use the guidance on Operational limits for Business Central online<../administration/operational-limits-online>. For advanced analysis, consider using a queueing model such as a M/M/1 queue<https://en.wikipedia.org/wiki/M/M/1_queue> to answer whether the system can process the workload you intend.\n### Performance telemetry\nThe following performance telemetry is available in Azure Application Insights (if that has been configured for the environment):\n Database locks\n Long running AL operations\n Long running SQL queries\n Page views\n Reports\n Sessions started\n Web service requests\nLearn more in the performance-work-perf-problem#analyzing-performance-issues-using-telemetry section.\n### Troubleshooting\nThe following articles can be of help in troubleshooting performance issues:\n Find missing SIFT indexes for FlowFields by disabling SmartSQL<../administration/troubleshooting-queries-involving-flowfields-by-disabling-smartsql>\n Use the Performance Profiler to analyze a slow scenario<../administration/performance-profiler-overview>\n Viewing table sizes</admin-view-table-information>\n## Tuning the development environment\nThe following articles explain what you can do as a developer to tune your development environment for better performance:\n Optimizing Visual Studio Code for AL development<../developer/devenv-optimize-visual-studio-code>\n ../developer/devenv-using-code-analysis-tool#enable-code-analysis-on-large-projects\n## Related information\nperformance-overview\nHow application configurations affect performance<performance-application>\nperformance-online\nPerformance of on-premises installations<performance-onprem>\nperformance-work-perf-problem\nPerformance tips for business users<performance-users>\n../administration/database-missing-indexes\n../administration/optimize-sql-al-database-methods-and-performance-on-server"}