<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rajnarayanan Ramanathan on Medium]]></title>
        <description><![CDATA[Stories by Rajnarayanan Ramanathan on Medium]]></description>
        <link>https://medium.com/@rajasabarish18?source=rss-16ed00cedd1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Rajnarayanan Ramanathan on Medium</title>
            <link>https://medium.com/@rajasabarish18?source=rss-16ed00cedd1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 06:41:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajasabarish18/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Queueable Apex: Transaction Finalizers]]></title>
            <link>https://medium.com/@rajasabarish18/mastering-queueable-apex-transaction-finalizers-13aae39b8fb6?source=rss-16ed00cedd1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/13aae39b8fb6</guid>
            <category><![CDATA[salesfroce]]></category>
            <category><![CDATA[salesforce-apex]]></category>
            <category><![CDATA[queueable]]></category>
            <dc:creator><![CDATA[Rajnarayanan Ramanathan]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 15:31:09 GMT</pubDate>
            <atom:updated>2026-01-26T15:31:09.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_hTiixFwqsMeZhYSDFlfQ.png" /></figure><h4>Introduction</h4><p>Welcome back! In my previous blogs, we explored <a href="https://medium.com/@rajasabarish18/understanding-apex-cursors-in-salesforce-92018e841d29"><strong>Understanding Apex Cursors</strong></a> and compared them in <a href="https://medium.com/@rajasabarish18/apex-cursors-vs-batch-apex-when-to-use-which-bcd6d9639251"><strong>Apex Cursors vs Batch Apex</strong></a>. Today, we are diving into another powerful tool in the asynchronous Apex toolkit: <strong>Transaction Finalizers</strong>.</p><p>As Salesforce developers, we often rely on asynchronous processes to handle complex operations. While tools like Queueable Apex have improved how we handle these background processes, they introduce specific challenges regarding reliability and error handling.</p><h4>Problem Statement</h4><p>If you have worked with <strong>Queueable Apex</strong>, you are likely familiar with its “fire and forget” nature. While efficient, this architecture creates a significant blind spot: <strong>“What happens if my job fails?”</strong></p><p>Before the introduction of Transaction Finalizers, handling failures in Queueable Apex was notoriously difficult. If a job crashed due to an unhandled exception (such as a row lock or a validation error), the developer had no immediate mechanism to detect or recover from that failure within the platform.</p><p>You were often forced to:</p><ul><li>Implement complex “polling” mechanisms to check the AsyncApexJob table.</li><li>Manually query logs after the fact.</li><li>Leave data in an inconsistent state until a user reported the issue.</li></ul><h4>What Is an Transaction Finalizer?</h4><p>A <strong>Transaction Finalizer</strong> acts as a guaranteed post-execution step for your Queueable jobs.</p><p>It is a specialized interface System.Finalizer that you attach to a Queueable job. Salesforce ensures that the Finalizer logic executes after the Queueable job completes, regardless of whether the job finished successfully or failed with an unhandled exception.</p><h4>Concept Explanation</h4><p>The core mechanism relies on the System.attachFinalizer() method. When you attach a finalizer, you are essentially telling Salesforce: <em>&quot;Once this job is done, run this specific piece of code.&quot;</em></p><p>Key components include:</p><ul><li><strong>The Interface:</strong> Your class must implement System.Finalizer.</li><li><strong>The Context:</strong> The execute method receives a FinalizerContext object, which provides the job&#39;s ID getAsyncApexJobId, the result getResult, and the exception details getException if one occurred.</li><li><strong>State Preservation:</strong> When you attach a finalizer, Salesforce serializes the state of the finalizer instance. This means you can pass data (like record lists or counters) from the Queueable job to the Finalizer.</li></ul><h4>Code Example</h4><p>Here is a robust pattern implementing a <strong>Retry Mechanism</strong> with a safety counter. This class implements both Queueable and Finalizer to share state easily.</p><pre>public class AccountUpdateJob implements Queueable, Finalizer {<br><br>    private List&lt;Account&gt; accountsToUpdate;<br>    private Integer retryCount;<br><br>    // 1. Default Constructor<br>    // Chains to the main constructor, initializing retryCount to 0.<br>    public AccountUpdateJob(List&lt;Account&gt; records) {<br>        this(records, 0);<br>    }<br><br>    // 2. Main Constructor<br>    // Preserves the retry counter across transaction boundaries.<br>    public AccountUpdateJob(List&lt;Account&gt; records, Integer retryCount) {<br>        this.accountsToUpdate = records;<br>        this.retryCount = retryCount;<br>    }<br><br>    // --- Queueable Logic ---<br>    public void execute(QueueableContext ctx) {<br>        // IMPORTANT: Attach the finalizer before performing operations.<br>        // We pass &#39;this&#39; so the Finalizer preserves current state (records + retryCount).<br>        System.attachFinalizer(this);<br><br>        System.debug(&#39;Attempt #&#39; + (retryCount + 1) + &#39; to update &#39; + accountsToUpdate.size() + &#39; accounts.&#39;);<br>        <br>        // Perform the update (Susceptible to row locks/validation errors)<br>        update accountsToUpdate; <br>    }<br><br>    // --- Finalizer Logic ---<br>    public void execute(FinalizerContext ctx) {<br>        String jobId = ctx.getAsyncApexJobId();<br>        <br>        // Check the result of the Queueable job<br>        switch on ctx.getResult() {<br>            when SUCCESS {<br>                System.debug(&#39;Success! Job &#39; + jobId + &#39; completed. Accounts updated.&#39;);<br>            }<br>            when UNHANDLED_EXCEPTION {<br>                // The job failed. Access the exception details.<br>                Exception ex = ctx.getException();<br>                System.debug(&#39;Job failed: &#39; + ex.getMessage());<br><br>                // RETRY LOGIC<br>                // Check if we have hit our maximum retry limit (e.g., 3 attempts)<br>                if (retryCount &lt; 3) {<br>                    System.debug(&#39;Retrying Account Update Job...&#39;);<br>                    <br>                    // Re-enqueue the job with the SAME list but INCREMENTED counter<br>                    System.enqueueJob(new AccountUpdateJob(this.accountsToUpdate, this.retryCount + 1));<br>                } else {<br>                    System.debug(&#39;Max retries reached. Logging final error to database...&#39;);<br>                    // Logic to log a permanent error record.<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>How This Code Works</h4><ol><li><strong>Initialization:</strong> The job starts with retryCount = 0.</li><li><strong>Attachment:</strong> Inside execute(QueueableContext), we call System.attachFinalizer(this). This saves the current list of accounts and the current retry count.</li><li><strong>Failure Simulation:</strong> If update accountsToUpdate throws an error (e.g., a Row Lock), the Queueable job terminates.</li><li><strong>Finalizer Trigger:</strong> Salesforce immediately starts a new transaction for the Finalizer.</li><li><strong>Recovery:</strong> The Finalizer checks ctx.getResult(). Seeing a failure, it checks if retryCount &lt; 3.</li><li><strong>Re-enqueue:</strong> It queues a <em>new</em> instance of the job, passing retryCount + 1. This loop continues until success or the limit is reached.</li></ol><h4>Important Limitations</h4><p>According to Salesforce documentation, you must be aware of these strict limits:</p><ol><li><strong>One Finalizer Per Job:</strong> You can only attach a single finalizer instance to any given Queueable job. Attempting to attach a second one will cause the job to fail with the error message: <em>More than one Finalizer cannot be attached to same Async Apex Job</em>.</li><li><strong>The “5-Consecutive-Failures” Limit:</strong> While you can chain successful Queueable jobs almost indefinitely, retries are strictly limited. If a job fails and your Finalizer starts a new one, Salesforce counts this as a retry. If this happens <strong>5 times in a row</strong>, Salesforce stops the chain to prevent an infinite error loop.</li><li><strong>Transaction Limits:</strong></li></ol><ul><li>The Finalizer runs in a <strong>new transaction</strong>.It generally enforces Synchronous Apex limits.</li><li><strong>Exception:</strong> You <em>do</em> get the larger <strong>Asynchronous Heap Size (12 MB)</strong>.</li></ul><h4>When to Use Transaction Finalizers ?</h4><ol><li><strong>Recovery &amp; Retry:</strong> When a job might fail due to temporary issues (row locks, external API timeouts) and needs to be retried automatically.</li><li><strong>Logging:</strong> When you need to capture specific exception messages from asynchronous failures into a custom “Error Log” object.</li><li><strong>Cleanup:</strong> When you need to release resources or send a “Job Complete” email regardless of success or failure.</li></ol><h4>When NOT to Use</h4><ol><li><strong>Batch Apex Alternatives:</strong> If you are processing thousands of records and need robust failure handling, <strong>Batch Apex</strong> is often better because it handles chunking and partial failures natively Database.Stateful.</li><li><strong>Infinite Loops:</strong> Do not use Finalizers to chain jobs indefinitely without a counter or exit condition.</li></ol><h4>Best Practices</h4><ol><li><strong>Idempotency:</strong> Ensure your Queueable logic is idempotent. If a job fails halfway through, retrying it should not duplicate data or corrupt the state.</li><li><strong>Limit Retry Counts:</strong> Always implement a manual counter (like the retryCount in the example) to avoid wasting resources on &quot;hard&quot; errors that will never succeed.</li><li><strong>Lightweight Finalizers:</strong> Keep the Finalizer logic simple (logging, queuing). Do not perform heavy processing in the Finalizer itself.</li></ol><h4>Common Mistakes</h4><ol><li><strong>Assuming Async Limits:</strong> Developers often assume the Finalizer has 60 seconds of CPU time because it follows a Queueable job. <strong>It does not.</strong> It has the standard synchronous CPU limit (10 seconds).</li><li><strong>Attaching Too Late:</strong> If the exception occurs <em>before</em> System.attachFinalizer() is called, the Finalizer will never run. Always attach it at the very beginning of your execute method.</li></ol><h4>Conclusion / Key Takeaways</h4><p>Transaction Finalizers transform Queueable Apex from a “fire and forget” tool into a resilient, enterprise-grade solution. By implementing the retry pattern shown above, you can build self-healing applications that handle temporary failures gracefully without user intervention.</p><ol><li><strong>Attach Early:</strong> Always attach the finalizer first.</li><li><strong>Count Your Retries:</strong> Avoid infinite loops.</li><li><strong>Know Your Limits:</strong> Respect the synchronous nature of the Finalizer transaction.</li></ol><p>Happy Coding! ☁️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13aae39b8fb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apex Cursors vs. Batch Apex: When to use which?]]></title>
            <link>https://medium.com/@rajasabarish18/apex-cursors-vs-batch-apex-when-to-use-which-bcd6d9639251?source=rss-16ed00cedd1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd6d9639251</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce-apex]]></category>
            <dc:creator><![CDATA[Rajnarayanan Ramanathan]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 09:37:33 GMT</pubDate>
            <atom:updated>2026-01-17T09:46:55.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qeh2om0rCs5e2gC-mk0ruQ.png" /></figure><p>Welcome back! In my <a href="https://medium.com/@rajasabarish18/understanding-apex-cursors-in-salesforce-92018e841d29">first blog</a>, we explored <strong>Apex Cursors</strong> — the shiny new tool in the Salesforce developer’s toolkit.</p><p>But now, the big question is: <strong>“We already have Batch Apex. Why do we need Cursors? And when should I use one over the other?”</strong></p><p>If you are confused between the old reliable “Batch Apex” and the modern “Apex Cursor,” this guide is for you. Let’s break it down in simple English.</p><h3><strong>The Basics: What are they?</strong></h3><h4><strong>Batch Apex (The Heavy Lifter)</strong></h4><p>Think of Batch Apex as a <strong>cargo train</strong>. It is designed to carry a massive amount of data (up to 50 million records) from Point A to Point B. It breaks the data into small “batches” (usually 200 records at a time) and processes them one by one in the background. It’s powerful, but it can be slow and heavy to execute.</p><h4><strong>Apex Cursors (The Smart Stream)</strong></h4><p>Think of Apex Cursors as a <strong>streaming service</strong> (like Netflix). Instead of downloading the whole movie (all records) at once, it buffers just what you need, right when you need it. It allows you to grab a specific chunk of data from a massive query instantly, without the heavy overhead of a Batch job.</p><h3>Key Differences at a Glance</h3><figure><img alt="Comparison table of Salesforce Apex Cursors vs Batch Apex limits and features." src="https://cdn-images-1.medium.com/max/1024/1*fl6DIdhBZ2c_iHhd91-qkg.png" /></figure><h3>The Nitty-Gritty: Limits You Must Know (Important!)</h3><p>This is where the difference usually bites you. Before you choose, look at these numbers.</p><h4><strong>Batch Apex Limits (The “Fresh Start” Advantage)</strong></h4><p>The superpower of Batch Apex is that it <strong>resets</strong> your Governor Limits for every chunk</p><ul><li><strong>CPU Time:</strong> You get a fresh <strong>60 seconds</strong> for <em>each</em> batch.</li><li><strong>Heap Size:</strong> You get a fresh <strong>12 MB</strong> of memory for <em>each</em> batch.</li><li><strong>The Trade-off:</strong> You can only have <strong>5 active jobs</strong> running at once, and up to <strong>100</strong> in the holding queue. If the queue is full, your job waits.</li></ul><h4><strong>Apex Cursor Limits (The “Shared” Constraint)</strong></h4><p>Apex Cursors are fast, but they don’t give you a “fresh start.” They share the limits of the transaction they are running in.</p><ul><li><strong>Fetch Limit:</strong> You can only call .fetch() <strong>10 times</strong> in a single transaction.</li><li><strong>Memory/CPU:</strong> Limits <strong>do not</strong> reset between fetches. If you fetch 10 massive chunks sequentially in a single transaction, you might hit the 10-second CPU limit.</li><li><strong>Max Cursors per day:</strong> 10,000.</li><li><strong>Max Rows fetched per day:</strong> 100 Million (Org-wide limit).</li><li><strong>Max Rows per Cursor:</strong> 50 Million (Same as Batch Apex).</li></ul><blockquote><em>Since Cursors share limits, you cannot process 50 million records in a single synchronous transaction. You must combine Cursors with a </em><strong><em>Queueable</em></strong><em> class to process them in chunks effectively.</em></blockquote><h3>When to use Batch Apex?</h3><p>Stick with the classic <strong>Batch Apex</strong> if:</p><ul><li><strong>You need to update/delete millions of records.</strong> Because each batch gets fresh limits, it is the safest way to do heavy database work.</li><li><strong>You need “State.”</strong> If you need to count records or sum up numbers across all batches (using Database.Stateful), Batch Apex has this built-in.</li><li><strong>You need reliability over speed.</strong> Batch jobs have built-in retry mechanisms if a chunk fails.</li></ul><h4><strong>Example Batch Scenario:</strong></h4><blockquote>“I need to update the ‘Status’ field on 15 million old Case records every night.”</blockquote><h3>When to use Apex Cursors?</h3><p>Switch to <strong>Apex Cursors</strong> if:</p><ul><li><strong>You need speed.</strong> Cursors are incredibly fast at fetching data compared to the start-up time of a Batch job. You don’t have to wait in the “Flex Queue” like a Batch job.</li><li><strong>You are building a UI.</strong> If you have a Lightning Web Component (LWC) that needs to display a list of 50,000 records with <strong>custom</strong> ‘Next/Previous’ pagination, Cursors are perfect.</li><li><strong>The “Queueable Chain” Pattern.</strong> A modern pattern is to use a <strong>Queueable</strong> job that fetches a chunk using a Cursor, processes it, and then chains itself again. This is often faster than Batch Apex.</li></ul><h4><strong>Example Cursor Scenario:</strong></h4><blockquote>“I need to process 10,000 records and send them to an external API, and I want it done ASAP.”</blockquote><p>Note: Cursors are stateless. You must manage your own state if chaining jobs.</p><h3>Code Showdown</h3><h4><strong>The Batch Way (Old School):</strong></h4><p>You have to write a full class implementing Database.Batchable, with start, execute, and finish methods. It’s a lot of boilerplate code!</p><h4><strong>The Cursor Way (New School):</strong></h4><p>It is much simpler and can be written in a few lines.</p><pre>// Define the query<br>String query = &#39;SELECT Id, Name FROM Account&#39;;<br><br>// Create the cursor<br>Database.Cursor cursor = Database.getCursor(query);<br><br>// Fetch just the records you need (e.g., skip 100, fetch 50)<br>List&lt;Account&gt; myChunk = cursor.fetch(100, 50);<br><br>// Process them immediately<br>for(Account acc : myChunk) {<br>    System.debug(&#39;Processing: &#39; + acc.Name);<br>}</pre><h3>Conclusion</h3><ul><li><strong>Use Batch Apex</strong> for heavy, long-running maintenance tasks (like nightly data cleanups).</li><li><strong>Use Apex Cursors</strong> for high-performance reading, custom UI pagination, or modern async processing.</li></ul><p>Salesforce is giving us more options to write better code. Cursors don’t replace Batch Apex entirely, but they definitely replace it for many lightweight tasks!</p><p>Happy Coding! ☁️</p><p>If you found this helpful, check out my previous blog on <a href="https://medium.com/@rajasabarish18/understanding-apex-cursors-in-salesforce-92018e841d29">Understanding Apex Cursors</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd6d9639251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Apex Cursors in Salesforce]]></title>
            <link>https://medium.com/@rajasabarish18/understanding-apex-cursors-in-salesforce-92018e841d29?source=rss-16ed00cedd1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/92018e841d29</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[apex]]></category>
            <dc:creator><![CDATA[Rajnarayanan Ramanathan]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 12:28:56 GMT</pubDate>
            <atom:updated>2026-01-15T08:37:12.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRdHSJjuzenCm1C_io1fHA.png" /></figure><h3><strong>Introduction</strong></h3><p>When working with large data sets in Salesforce, developers often face heap size and query row limit issues. Querying a large number of records using a normal SOQL query can quickly lead to governor limit exceptions if all records are loaded into memory at once.</p><p>Apex Cursors help address this problem by allowing query results to be accessed incrementally, instead of loading the entire result set into memory.</p><p>In this blog, we’ll understand what Apex Cursors are, how they work, and when to use them, with a simple and practical example.</p><h3><strong>Problem Statement</strong></h3><p>Salesforce enforces strict governor limits to ensure platform stability. When querying large data volumes, developers may encounter issues such as:</p><ul><li>Heap size limit exceptions.</li><li>Query row limit exceptions.</li></ul><p>Using a standard SOQL query in such scenarios is often not sufficient, especially when the result set is large.</p><h3><strong>What Is an Apex Cursor?</strong></h3><p>An Apex Cursor is a Salesforce-provided mechanism that enables incremental access to query results. Instead of loading all records into memory, records are retrieved in portions as requested.</p><p>Apex Cursors control <strong>how query results are fetched</strong>, not how execution limits are managed.</p><p>Salesforce provides Apex Cursor functionality through the Database.Cursor() type as part of the Apex platform APIs.</p><p>This functionality:</p><ul><li>Maintains the query result set server-side.</li><li>Retrieves records only when requested.</li><li>Allows developers to control how many records are fetched at a time.</li></ul><p><strong>Important: </strong>Apex Cursors help mitigate heap size and query row limits, but they do not reset CPU time or DML limits.</p><h3><strong>Concept Explanation</strong></h3><p>Using this approach, developers can retrieve a defined number of records at a time by calling the fetch() method. The cursor maintains its position within the query result set, allowing records to be accessed incrementally across executions.</p><p>This approach:</p><ul><li>Prevents loading the entire result set into heap memory.</li><li>Enables controlled access to large datasets.</li><li>Is commonly used with asynchronous Apex patterns such as Queueable Apex.</li></ul><h3><strong>Code Example</strong></h3><pre>public class ApexCursorsBeginner implements Queueable {<br>    <br>    // Apex Cursor<br>    private Database.Cursor cursor;<br>    <br>    // Tracks current cursor position<br>    private Integer position;<br>    <br>    // Number of records fetched per execution<br>    private static final Integer CHUNK_SIZE = 200;<br>    <br>    // Constructor - initialize cursor and position<br>    public ApexCursorsBeginner() {<br>        this.cursor = Database.getCursor(<br>            &#39;SELECT Id, LastActivityDate FROM Contact WHERE LastActivityDate = LAST_N_DAYS:400&#39;<br>        );<br>        this.position = 0;<br>    }<br>    <br>    // Overloaded constructor for chaining<br>    public ApexCursorsBeginner(Database.Cursor cursor, Integer position) {<br>        this.cursor = cursor;<br>        this.position = position;<br>    }<br>    <br>    public void execute(QueueableContext context) {<br>        try {<br>            // Fetch next chunk of records<br>            List&lt;Contact&gt; scope = cursor.fetch(position, CHUNK_SIZE);<br>            <br>            // Move cursor forward<br>            position += scope.size();<br>            <br>            // ---- Governor Limit Checks ----<br>            if (Limits.getCpuTime() &gt; Limits.getLimitCpuTime() * 0.8) {<br>                System.debug(&#39;CPU limit nearing threshold.&#39;);<br>                return;<br>            }<br>            <br>            if (Limits.getDmlRows() &gt; Limits.getLimitDmlRows() * 0.8) {<br>                System.debug(&#39;DML rows limit nearing threshold.&#39;);<br>                return;<br>            }<br>            <br>            // ---- Business Logic (Light Processing) ----<br>            for (Contact con : scope) {<br>                // Example: just log or mark records<br>                System.debug(&#39;Processing Contact: &#39; + con.Id);<br>            }<br>            <br>            // ---- Chain next Queueable job if records remain ----<br>            // ---- Max chain depth is 50 ----<br>            // Queueable runs in a single transaction, so limits must be monitored manually<br>            if (position &lt; cursor.getNumRecords()) {<br>                System.enqueueJob(<br>                    new ApexCursorsBeginner(cursor, position)<br>                );<br>            }<br>            <br>        } catch (System.TransientCursorException e) {<br>            // This is a temporary issue. The transaction can be retried.<br>            System.debug(&#39;Transient error occurred: &#39; + e.getMessage());<br>            <br>            // Retry logic: Re-enqueue the job with the CURRENT position (do not increment)<br>            System.enqueueJob(new ApexCursorsBeginner(cursor, position));<br>            <br>        } catch (System.FatalCursorException e) {<br>            // This is a non-recoverable error. Log and abort.<br>            System.debug(&#39;Fatal cursor error: &#39; + e.getMessage());<br>            // Do not retry.<br>            <br>        } catch (Exception e) {<br>            // Handle any other unexpected exceptions<br>            System.debug(&#39;General exception: &#39; + e.getMessage());<br>        }<br>    }<br>}</pre><h3><strong>How This Code Works</strong></h3><h4><strong>Cursor Creation</strong></h4><pre>Database.Cursor cursor = Database.getCursor(soql);</pre><ul><li>The query result set is maintained server-side.</li><li>Records are retrieved only when requested.</li></ul><h4><strong>Controlled Record Retrieval</strong></h4><pre>cursor.fetch(position, CHUNK_SIZE);</pre><ul><li>Records are fetched in fixed-size sets.</li><li>The fetch size is fully controlled by the developer.</li></ul><h4><strong>Multiple Transactions via Queueable Chaining</strong></h4><pre>System.enqueueJob(new ApexCursorsBeginner(cursor, position));</pre><ul><li>Each Queueable execution runs in a separate transaction.</li><li>Governor limits are reset for each execution.</li></ul><h4>Apex Cursor Exceptions</h4><p>Salesforce Apex Cursors can throw two specific system exceptions which you should handle in your code:</p><p>System.TransientCursorException</p><ul><li><strong>Description:</strong> This exception indicates a temporary issue, such as a momentary loss of connectivity or a transient internal state error.</li><li><strong>Handling:</strong> Transactions that fail with this exception <strong>can be retried</strong>. Since the error is temporary, re-attempting the operation (fetching the records again) will likely succeed.</li></ul><p>System.FatalCursorException</p><ul><li><strong>Description:</strong> This exception indicates a critical, non-recoverable error. This could happen if the cursor has expired, the query is invalid, or the cursor was created with invalid options.</li><li><strong>Handling:</strong> These errors <strong>cannot be retried</strong>. You should catch this exception, log the error, and gracefully abort the operation.</li></ul><h3><strong>Important Limitations</strong></h3><p>When using Apex Cursors with Queueable Apex, the following constraints apply:</p><ul><li>Queueable jobs can be chained(unlimited in Prod) and enqueue<em> </em>limit(50 per transaction).</li><li>Cursor state must be serializable.</li><li>There is no built-in retry mechanism or completion callback.</li><li>Error handling must be implemented explicitly.</li><li>Cursors expire after 48 hours (relevant for very long-running chains).</li></ul><p>These constraints should be carefully considered during design.</p><h3>When to Use Apex Cursors</h3><ul><li>When working with very large query result sets.</li><li>When heap size or query row limits are a concern.</li><li>When incremental access to query results is required.</li></ul><h3><strong>When NOT to Use</strong></h3><ul><li>Small datasets.</li><li>Simple queries.</li><li>Scenarios where Batch Apex already meets the requirement.</li></ul><h3><strong>Best Practices</strong></h3><ul><li>Test thoroughly with large datasets.</li><li>Combine Apex Cursors with appropriate asynchronous Apex patterns (such as Queueable or Batch Apex) based on the use case.</li><li>Monitor governor limits.</li><li>Prefer Batch Apex for large-scale or long-running data processing.</li></ul><h3><strong>Common Mistakes</strong></h3><ul><li>Using Apex Cursors for small or simple queries.</li><li>Assuming Apex Cursors reset CPU or DML limits.</li><li>Treating Apex Cursors as a replacement for Batch Apex.</li></ul><h3><strong>Conclusion / Key Takeaways</strong></h3><p>Apex Cursors provide a controlled way to access large query result sets without loading all records into memory. While they help address heap size and query row limits, they do not manage execution limits on their own.</p><p>When used appropriately with asynchronous Apex, Apex Cursors can be an effective tool for handling large data volumes in Salesforce.</p><h3><strong>Call to Action</strong></h3><p>If you found this helpful, feel free to clap, share, or leave a comment. Let’s learn Salesforce together 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92018e841d29" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>