<?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 Sharmarajat on Medium]]></title>
        <description><![CDATA[Stories by Sharmarajat on Medium]]></description>
        <link>https://medium.com/@sharmarajat1984?source=rss-12da1fe2c6a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9kOvr3h7-OiZuJZzXpy1eQ@2x.jpeg</url>
            <title>Stories by Sharmarajat on Medium</title>
            <link>https://medium.com/@sharmarajat1984?source=rss-12da1fe2c6a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:53:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharmarajat1984/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[Agentforce Vibes SOQL Builder Do It for You]]></title>
            <link>https://medium.com/@sharmarajat1984/agentforce-vibes-soql-builder-do-it-for-you-74cc7f328d06?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/74cc7f328d06</guid>
            <category><![CDATA[soql-editor]]></category>
            <category><![CDATA[agentforce-vibe]]></category>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 08:17:09 GMT</pubDate>
            <atom:updated>2026-06-09T08:17:09.583Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Salesforce architect, speed and accuracy inside the development loop matter enormously. Every minute spent context-switching out of VS Code — to Developer Console, Workbench, or a browser tab — is a minute not spent designing solutions. That’s why when I set up a new dev environment, the <strong>SOQL Builder</strong> inside the <strong>Agentforce Vibes</strong> VS Code extension is one of the first things I install.</p><p>It’s a visual, form-driven query builder that generates clean, valid SOQL in real time — right inside your editor — and pairs seamlessly with the SFDX CLI to execute queries against your connected org without ever leaving VS Code. If you’re building agents, Apex, flows, or Data Cloud pipelines, this belongs in your toolkit.</p><p>Let me walk you through exactly how it works.</p><h3>What Is Agentforce Vibes?</h3><p>Agentforce Vibes is a VS Code extension purpose-built for Salesforce developers and architects working in the Agentforce / agentic AI era. Think of it as your IDE co-pilot for building on the Salesforce platform — it surfaces quick access to SOQL querying, org metadata management, and Agentforce DX tooling right inside your editor.</p><p>The SOQL Builder is one of its standout features: a visual, form-based query builder that generates clean, valid SOQL in real time as you configure your query — no raw syntax required.</p><h3>Step 1: Create a Query File via the Command Palette</h3><p>Everything starts from the <strong>Command Palette</strong>. Hit Cmd+Shift+P (Mac) or Ctrl+Shift+P (Windows/Linux) and type S. Two SOQL-related commands surface immediately: <strong>SFDX: Create Query in SOQL Builder</strong> and <strong>SFDX: Execute SOQL Query with Current File</strong> (more on the second one in Step 4).</p><p>Select <strong>SFDX: Create Query in SOQL Builder</strong>. VS Code will then prompt you for two things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bhrmxn7kgc6QvBlHwnAnJw.png" /></figure><ol><li><strong>File name</strong> — give it something descriptive, like Task1 or GetClosedCases. The extension automatically appends the .soql extension for you.</li><li><strong>Save location</strong> — choose the folder where you want the file to live. I typically drop mine under scripts/soql/ to keep query files organized separately from Apex classes and metadata.</li></ol><p>Once you confirm, VS Code opens the file and launches the visual SOQL Builder interface — and you’re ready to build.</p><blockquote><strong><em>Pro tip:</em></strong><em> The </em><em>.soql file is a real, committed file in your project. It lives in your repo, travels with your source control history, and can be rerun against any connected org at any time. Treat your SOQL files the same way you&#39;d treat scripts in any other language — name them clearly, review them in PRs, and keep them close to the code that uses them.</em></blockquote><h3>Step 2: Build Your Query Visually</h3><p>This is where the magic happens. The SOQL Builder gives you a clean, structured form that maps directly to SOQL clause by clause. Here’s a real example — querying closed Cases — to show exactly what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-AO5GtF1ha67uXbkrqyLw.png" /></figure><h3>From</h3><p>Start by selecting your <strong>object</strong>. Click the “From” dropdown and pick Case — or search for any standard or custom object in your connected org. The builder queries your actual org metadata dynamically, so the field list you see is always accurate to your current schema.</p><h3>Fields</h3><p>Click <strong>Search fields…</strong> and start typing field names. You can add as many as you need. In this example I selected:</p><ul><li>Id</li><li>Subject</li><li>Status</li><li>IsClosed</li></ul><p>Each field appears as a removable chip. Clean, visual, and — critically — no typos.</p><h3>Filter</h3><p>Here’s where it gets genuinely useful. Instead of wrestling with WHERE clause syntax, you get a structured filter builder with three columns: <strong>Field</strong>, <strong>Operator</strong>, and <strong>Value</strong>.</p><p>I set:</p><ul><li>Field: IsClosed</li><li>Operator: =</li><li>Value: TRUE</li></ul><p>Notice the <strong>AND / OR toggle</strong> at the top of the filter section — flip between them to change the logical operator applied across all your conditions. Need more conditions? Hit <strong>Add</strong> and another row appears. No parentheses to balance, no typos in field names.</p><h3>Order By and Limit</h3><p>The builder also exposes ORDER BY (with direction and null-handling dropdowns) and a LIMIT field. For quick exploratory queries I often skip these, but for anything going into a trigger or batch job context they&#39;re essential to set explicitly.</p><h3>The Live SOQL Preview</h3><p>As you configure each clause, the <strong>SOQL Query</strong> panel on the right updates in real time:</p><pre>SELECT Id, Subject, Status, IsClosed<br>  FROM Case<br>  WHERE IsClosed = TRUE</pre><p>Clean. Readable. Correct. You can copy this directly from the preview panel into an Apex class, a Flow SOQL query node, or a data export tool — exactly as generated.</p><h3>Step 3: Toggle Between SOQL Builder and Text Editor</h3><p>This is the feature I appreciate most as an architect who works across both visual tooling and raw code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*avKU3SZRLIVSJcIhkwzX9Q.png" /></figure><p>In the top-right corner of the editor tab there’s a small icon labelled <strong>“Switch Between SOQL Builder and Text Editor”</strong>. Click it and the view flips — same .soql file, same content, but now displayed as a raw text editor in VS Code. From here you can:</p><ul><li><strong>Hand-edit the SOQL directly</strong> — add subqueries, use TYPEOF, write HAVING clauses, or anything the visual builder doesn’t yet surface in the UI</li><li><strong>Copy the query</strong> into Apex, an anonymous window, or a data export tool</li><li><strong>Edit and flip back</strong> — the builder re-parses your updated text and reflects the changes in the visual form when you toggle back</li></ul><p>This bidirectional workflow is the key insight: <strong>the builder isn’t a black box</strong>. It’s a companion to the text editor, not a replacement. My typical flow is:</p><ol><li>Start in the <strong>SOQL Builder</strong> to scaffold the query structure quickly — object, fields, basic filters</li><li><strong>Toggle to text editor</strong> to fine-tune — add a subquery, tweak an operator, add an ORDER BY with NULLS LAST</li><li><strong>Toggle back to visual</strong> to double-check the filter logic reads the way I intended</li></ol><p>You get the speed of the visual builder and the precision of the text editor, without ever leaving the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RNe21N3lndNXwNMsimEdg.png" /></figure><h3>Step 4: Execute the Query Using the SFDX Command</h3><p>Once your .soql file is open in the <strong>text editor view</strong>, you can run it directly against your connected org — no switching to Developer Console, no copy-pasting into Workbench.</p><p>Open the Command Palette again, type S, and select <strong>SFDX: Execute SOQL Query with Current File</strong>.</p><p>The extension sends the query to your default org and streams the results back into the <strong>Output</strong> panel at the bottom of VS Code. You get a clean JSON-formatted result set, total record count, and any API errors — right inside your editor. No browser tabs, no sessions to manage, no context switching.</p><p>This is particularly powerful when you’re iterating quickly during development. The full loop looks like:</p><ol><li>Build in <strong>SOQL Builder</strong> → get the structure right visually</li><li><strong>Toggle to text</strong> → fine-tune the query</li><li>Run <strong>SFDX: Execute SOQL Query with Current File</strong> → see results in Output panel</li><li>Adjust → re-run → repeat</li></ol><p>The entire query-test-iterate loop lives inside VS Code. Once you work this way, going back to Developer Console feels like a step backward.</p><h3>Why This Matters Beyond Quick Queries</h3><p>I work across large-scale Salesforce transformations — multi-cloud implementations, Data Cloud pipelines, Agentforce agent design, MuleSoft integrations. At that scope, the queries I write aren’t just exploratory one-offs. They become the foundation for:</p><ul><li><strong>Apex batch queries</strong> that process millions of records — getting the filter right the first time matters</li><li><strong>Data Cloud ingestion filters</strong> — what gets unified starts with what you query</li><li><strong>Agent action inputs</strong> — SOQL-backed data lookups that drive autonomous Agentforce decisions</li><li><strong>Governance checkpoints</strong> — query plans that need architect review before hitting production</li></ul><p>Having .soql files committed to the repo, version-controlled alongside the code that uses them, makes that governance conversation much cleaner. A Pull Request that includes both the Apex batch class and the GetClosedCases.soql file it runs is a far more reviewable artifact than a query buried inside a Java string literal in a trigger.</p><p>The SOQL Builder makes writing that first clean query fast enough that you’ll actually do it as a proper file — not as a throwaway string you’ll clean up later (and never do).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74cc7f328d06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When the Event Bus Blinks: Building Resilient Callback and Retry Mechanisms for Salesforce Platform…]]></title>
            <link>https://medium.com/@sharmarajat1984/when-the-event-bus-blinks-building-resilient-callback-and-retry-mechanisms-for-salesforce-platform-69fe1262b1f9?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/69fe1262b1f9</guid>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Fri, 22 May 2026 00:57:11 GMT</pubDate>
            <atom:updated>2026-05-22T00:57:11.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>When the Event Bus Blinks: Building Resilient Callback and Retry Mechanisms for Salesforce Platform Events</h3><p>Symptoms :</p><ol><li>If you have missing PE, where it is not published or downstream system complaint about it.</li><li>Periodically check with salesforce support and ask, can you let us know if there is any Event failed on the Event Bus on the salesforce side (provide your PE Api Name) in the last 7 days or 15 days.</li></ol><p><strong><em>An architecture deep-dive on surviving transient Event Bus infrastructure failures using Apex Publish Callbacks.</em></strong></p><p>There is a particular kind of production incident that humbles even seasoned platform teams. Nothing in your code changed. Your tests still pass. Your event definitions are untouched. And yet, for a window of several minutes, a slice of your Platform Events simply never made it to their subscribers. No exception bubbled up to your publishing transaction. The Database.SaveResult came back clean. Everything <em>looked</em> fine.</p><p>This is the failure mode that most Salesforce integration architectures are quietly unprepared for, and it is the one I want to walk through here — both the distributed-systems mechanics behind it and the concrete Apex patterns that let you survive it.</p><p>If you build event-driven integrations on Salesforce and you are still treating EventBus.publish() as if its return value confirms delivery, this is for you.</p><h3>The comfortable lie of “publish succeeded”</h3><p>Platform Events are Salesforce’s native pub/sub backbone. You define an event much like a custom object, publish instances of it from Apex, Flow, or the REST API, and one or more subscribers consume them independently and asynchronously. It is the mechanism of choice for decoupling systems: order capture from fulfillment, CDC-style propagation, fan-out to external middleware over the Pub/Sub API, internal orchestration between loosely coupled Salesforce modules.</p><p>The appeal is the decoupling. The risk lives in the same place.</p><p>Here is the detail that trips up most teams. <strong>Platform event publishing is always asynchronous.</strong> When you call EventBus.publish() in Apex, the Database.SaveResult you get back is <em>not</em> a delivery confirmation. It is an acknowledgment that your event was successfully <em>enqueued</em> for publication onto the event bus. The actual publishing happens later, in a separate operation, when system resources are available.</p><p>So the canonical defensive code that nearly everyone writes first:</p><p>apex</p><pre>List&lt;Database.SaveResult&gt; results = EventBus.publish(myEvents);<br>for (Database.SaveResult sr : results) {<br>    if (!sr.isSuccess()) {<br>        // handle failure<br>    }<br>}</pre><p>…only catches a narrow class of problems — things detectable at enqueue time, like a missing required field value. It tells you nothing about whether the event was ultimately published to the bus. If an internal system error prevents publication <em>after</em> enqueuing, that code never sees it. Salesforce’s own documentation is blunt about this: most of the time the eventual publishing succeeds and you never have to think about it, but in rare cases an internal system error causes the asynchronous publishing to fail, and that failure does not surface in the publish call result.</p><p>“Rare” is doing a lot of work in that sentence. And “rare” is exactly what bites you, because rare failures are the ones nobody designed for.</p><h3>Anatomy of a real Event Bus failure</h3><p>Let me make this concrete with a real-world incident pattern, because the abstract phrase “internal system error” hides a genuinely instructive distributed-systems cascade.</p><p>A post-incident investigation into an Event Bus disruption traced the root cause to <strong>hardware-level performance degradation on a single host</strong> within the eventing infrastructure. Not an outage — degradation. The host was still alive, still accepting traffic, but responding with extreme latency when accepting published events.</p><p>Here is how one slow box turned into a platform-level publishing disruption. Follow the chain, because each link is a textbook distributed-systems concept and understanding them changes how you design.</p><p><strong>1. Backpressure.</strong> The eventing tier could no longer accept data at normal speed. When a downstream component slows down but upstream producers keep pushing at full rate, the slowness propagates <em>backward</em> through the system. That backpressure landed on the application infrastructure responsible for managing the distributed in-memory buffers that hold event payloads before they are committed to the bus.</p><p><strong>2. Congestion misread as failure.</strong> As those buffers filled and application servers got congested, the system’s health-detection logic drew the wrong conclusion. Servers that were merely <em>busy</em> — stalled waiting on the slow eventing tier — looked <em>unresponsive</em>. The system concluded its active leaders were dead when they were only stuck.</p><p><strong>3. Leader election storms.</strong> That misdiagnosis triggered a leadership transition. In a distributed publishing system, a “leader” coordinates a partition of the publishing work; if a leader appears to fail, control is handed to another host. But the underlying latency had not gone away, so the new leader also looked unresponsive, which triggered <em>another</em> transition. The system entered a continuous cycle of leadership churn — repeatedly handing off control among hosts, none of which could actually make progress.</p><p><strong>4. Synchronization amplification.</strong> Here is the cruel part. Every leadership transition is not free. Each new leader has to synchronize state — it must retrieve the in-flight event payloads sitting in the in-memory buffers of <em>other</em> application servers to take over their work. So each churn cycle generated a burst of internal application-to-application network traffic to fetch those buffered payloads.</p><p><strong>5. Secondary congestion and the cascade.</strong> The flood of payload-fetch requests created a <em>second</em> layer of congestion, this time in the internal network between application servers. Under that secondary congestion, some fetch requests timed out. And when a payload-fetch request times out, the payload it was trying to retrieve becomes <strong>unretrievable</strong>. That subset of events could not be published. Cascading failure complete: a single slow host → backpressure → false failure detection → leadership churn → synchronization traffic → network congestion → lost payloads → publishing failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*e9p0yFR7bppiPN9gd6VhQA.png" /></figure><p>The lesson here is not “Salesforce is unreliable.” Salesforce’s event bus is extraordinarily reliable in aggregate. The lesson is that <strong>even a managed, mature, well-engineered SaaS platform is built on physical hardware that degrades</strong>, on distributed consensus that can mistake slow for dead, and on synchronization mechanisms that can amplify rather than dampen a local problem. The platform recovered on its own. The application teams that had no callback or replay strategy lost events permanently in the gap.</p><p>This is why the foundational principle of resilient event-driven design holds even on SaaS: <strong>never assume guaranteed delivery.</strong> Design as though any individual publish <em>can</em> silently fail, because occasionally it will.</p><h3>Why Publish Callbacks are the right primitive</h3><p>Salesforce’s answer to the “publish succeeded but did it really?” problem is <strong>Apex Publish Callbacks</strong>. They exist precisely to give you the <em>final</em> result of an asynchronous publish, not just the intermediate enqueue result.</p><p>You implement one or both of two interfaces:</p><ul><li>EventBus.EventPublishFailureCallback, with a void onFailure(EventBus.FailureResult result) method that fires when publishing ultimately fails.</li><li>EventBus.EventPublishSuccessCallback, with a void onSuccess(EventBus.SuccessResult result) method that fires on confirmed publication.</li></ul><p>When you publish with a callback attached, Salesforce invokes the appropriate method <em>after the real publishing outcome is known</em> — asynchronously, in a separate transaction. From SuccessResult or FailureResult you call getEventUuids() to retrieve the list of UUIDs for the events that succeeded or failed, and that is the hook on which you hang correlation, logging, retry, and dead-lettering.</p><p>A few architectural realities to internalize before you write a line of code, because each one shapes the implementation:</p><p><strong>Callbacks apply only to Apex.</strong> If you publish via Flow or the REST API, you do not get this mechanism. For any integration where delivery actually matters, that alone is an argument for routing publication through an Apex service layer rather than letting Flows publish directly.</p><p><strong>The callback runs in a different transaction and a different user context.</strong> This is the gotcha that causes the most production surprises. Your publishing code might run as any user, including a specific integration user. The callback, because it is asynchronous, <em>always</em> runs as the <strong>Automated Process</strong> user. There is no “created by” field on a platform event, so if you need to know <em>who</em> triggered the publication — for audit, for routing, for tenant context — you must capture it yourself and carry it into the callback. More on how below.</p><p><strong>You must obtain the UUID <em>before</em> publishing.</strong> Every platform event carries a UUID in a read-only EventUuid field. This is your correlation key — it is how you match a failure result back to the business meaning of the event that failed. But there is a sharp edge: if you construct your event the obvious way, with new Order_Event__e(...), the EventUuid field is <em>not</em> initialized until after EventBus.publish() runs — which is too late, because your callback needs the UUID at construction time to build its correlation map. The fix is to construct events using sObjectType.newSObject(), which initializes EventUuid <em>before</em> the publish call. Miss this and your correlation map will be full of null keys and you will lose a day to confusion.</p><h3>The callback lifecycle, end to end</h3><p>The correlation-aware pattern is a four-step lifecycle:</p><ol><li><strong>Assemble lightweight data objects holding the minimum event data.</strong> Do not stuff full event records into the callback. You want a small wrapper holding the EventUuid and just enough business context (an order ID, a tenant key) to identify and, if needed, republish the event.</li><li><strong>Instantiate the callback, passing those data objects in.</strong> Behind the scenes, the data your callback holds is <strong>persisted to the database</strong> so it survives the gap between your transaction and the asynchronous callback transaction. This persistence is exactly why payload size matters — see the limits section.</li><li><strong>Enqueue the events for publication</strong>, passing both the events and the callback instance to EventBus.publish().</li><li><strong>Handle the outcome.</strong> onSuccess or onFailure fires; you pull UUIDs via getEventUuids() and correlate them back to your stored data objects to decide what to do next.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHYvaa4nX9KoY2po7LxfpQ.png" /></figure><h3>The limits that will define your design</h3><p>This is the section that separates a demo from a production design. The callback mechanism is not free, and its constraints directly govern your throughput ceiling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*KFZ5fVanMwVPej9EcX5smA.png" /><figcaption>150 M— Because high volume PE license bought, deafult is 5M</figcaption></figure><p><strong>The 5 MB rolling 30-minute cumulative limit.</strong> All publish callback instances share a cumulative storage budget of <strong>5 MB over any trailing 30-minute window</strong>. Remember that each callback instance is persisted to the database to bridge the async gap — so the data you cram into your callbacks (your correlation maps, any context you carry) accumulates against this budget across <em>every</em> callback your org fires in that window. Blow past it and callbacks start failing, which means you lose your failure-detection mechanism precisely when you are publishing at high volume — i.e., exactly when you most need it. Salesforce’s own guidance is explicit: keep the UUID map small, store a record ID you can re-query rather than the full event field set, and treat the callback instance as something to keep lean.</p><p><strong>The out-of-box payload storage limit is 5 MB; it can be extended to as much as 200 MB.</strong> The default callback payload storage allocation is 5 MB. Salesforce can raise this — up to 200 MB — but only through a <strong>product exception approval process</strong>, not a self-service setting. Treat the 200 MB figure as a negotiated ceiling you request with justification through your account team, not a knob you turn. If your architecture <em>needs</em> the extension to function, that is a strong signal you should first reduce per-callback payload size, because you are likely storing too much in each instance.</p><p>The operational consequences of these limits are where the real architecture decisions live:</p><ul><li><strong>Memory pressure and callback saturation.</strong> Because callback state is persisted and shares a cumulative budget, a high-volume publishing burst can <em>saturate</em> the callback subsystem. The danger scenario: a spike drives heavy publishing, callbacks balloon in aggregate size, you approach the 5 MB/30-min ceiling, and new callbacks begin to fail. You have now lost observability into failures during your highest-risk window. This is the callback equivalent of a monitoring system that goes dark exactly when the outage starts.</li><li><strong>Throughput constraints.</strong> Tracking <em>successful</em> publishes through onSuccess is tempting but usually wrong at scale. Most publishes succeed, so onSuccess fires constantly and consumes your callback budget on non-events. For high-volume streams, track <strong>failures only</strong> via onFailure. Reserve onSuccess for low-volume, high-criticality flows where positive confirmation genuinely earns its cost.</li><li><strong>The minimal-payload discipline is not a style preference; it is a capacity strategy.</strong> Every byte you store per callback is a byte against a shared 5 MB budget. Storing a record ID and re-querying is not just cleaner — it is what keeps you under the ceiling at volume.</li></ul><p>The tradeoff to state plainly: <strong>more resilience instrumentation costs more callback budget.</strong> You cannot wrap everything in maximal tracking and also publish at maximal volume. You are explicitly choosing which event streams deserve the resilience overhead.</p><h3>Production implementation</h3><p>Below is a production-oriented implementation. It assumes a custom platform event Order_Event__e with an Order_Id__c field, plus two custom objects backing the resilience layer: Event_Publish_Log__c for failure logging and Event_Dead_Letter__c for events that exhaust their retries. Adapt names to your governance conventions.</p><p>I have deliberately built this around <strong>failure-only tracking with re-queryable correlation keys, bounded retries, and a dead-letter terminus</strong> — the three things a demo always omits and production always needs.</p><h3>The publisher service</h3><p>apex Refer — <a href="https://developer.salesforce.com/docs/atlas.en-us.260.0.platform_events.meta/platform_events/platform_events_publish_callback_example_correlate.htm">https://developer.salesforce.com/docs/atlas.en-us.260.0.platform_events.meta/platform_events/platform_events_publish_callback_example_correlate.htm</a></p><p>Apex Trigger Published PE</p><pre>trigger OrderTrigger on Order (after insert, after update) {<br>    Map&lt;String,String&gt; uuidMap = new Map&lt;String,String&gt;();<br>    List&lt;Order_Event__e&gt; events = new List&lt;Order_Event__e&gt;();<br>    <br>    for (Order o : Trigger.new) {<br>        Order_Event__e e = (Order_Event__e) <br>        Order_Event__e.sObjectType.newSObject(null, true);<br>        // Fill event field with Order Id<br>        e.Order_Id__c = o.Id; <br>        // Map event UUID -&gt; Order Id so we can look up later<br>        uuidMap.put(e.EventUuid, o.Id); <br>        events.add(e);<br>    }<br><br>    FailureCallbackWithCorrelation cb = new FailureCallbackWithCorrelation(uuidMap);<br>    List&lt;Database.SaveResult&gt; srs = EventBus.publish(events, cb);<br><br>    // Inspect immediate publish result<br>    for (Database.SaveResult sr : srs) {<br>        if (sr.isSuccess()) {<br>            System.debug(&#39;Successfully enqueued event.&#39;);<br>        } else {<br>            for(Database.Error err : sr.getErrors()) {<br>                System.debug(&#39;Error returned: &#39; + err.getStatusCode() + &#39; - &#39; + <br>                    err.getMessage());<br>            }<br>        }<br>    }<br>}</pre><h3>The failure callback</h3><pre>public class FailureCallbackWithCorrelation implements EventBus.EventPublishFailureCallback<br>{<br>    public static final Integer MAX_RETRIES = 2;<br>    private Integer retryCounter = 0;<br>    private Map&lt;String,String&gt; uuidMap;<br>    <br>    // Callback constructor<br>    public FailureCallbackWithCorrelation(Map&lt;String,String&gt; uuidMap) {<br>        this.uuidMap = uuidMap;<br>    }<br>    <br>    public void onFailure(EventBus.FailureResult result) {<br>        List&lt;String&gt; eventUuids = result.getEventUuids();<br>        Map&lt;String,String&gt; newUuidMap = new Map&lt;String,String&gt;();<br>        <br>        if (retryCounter &lt; MAX_RETRIES) {<br>            // Try to re-publish the failed events<br>            List&lt;Order_Event__e&gt; events = new List&lt;Order_Event__e&gt;();<br>            for (String uuid : eventUuids) {<br>                // Create a new event with the contents of the failed event<br>                Order_Event__e event = (Order_Event__e) <br>                    Order_Event__e.sObjectType.newSObject(null, true);<br>                // Fill event with the right order record Id<br>                event.Order_Id__c = uuidMap.get(uuid);  <br>                events.add(event);<br>                <br>                // Use a new map since the new event will have a different uuid<br>                newUuidMap.put(event.EventUuid, event.Order_Id__c);<br>            }<br>            // Replace old uuid map because we no longer need its contents<br>            uuidMap = newUuidMap;<br>            <br>            // Republish with the same callback passed in again as &#39;this&#39;<br>            System.debug(&#39;Republish &#39; + eventUuids.size() + &#39; failed events.&#39;);<br>            EventBus.publish(events, this); <br>            System.debug(&#39;Republish event for Order with Ids: &#39; + <br>                         String.join(uuidMap.values(), &#39;, &#39;));<br>            <br>            // Increase counter<br>            retryCounter++;<br>        } else {<br>            // Retry exhausted, log an error instead<br>            System.debug(eventUuids.size() + &#39; event(s) failed to publish after &#39; + <br>                         MAX_RETRIES + &#39; retries &#39; +<br>                         &#39;for Order with Ids: &#39; + String.join(uuidMap.values(), &#39;, &#39;));<br>        }<br>    }<br>    <br>    // Getter methods so we can validate this in the unit test<br>    public Integer getRetryCounter() {<br>        return retryCounter;<br>    }<br><br>    public Map&lt;String,String&gt; getUuidMap() {<br>        return uuidMap;<br>    }<br>}</pre><p>A few implementation notes worth calling out, because they are the difference between a pattern that holds under load and one that makes things worse:</p><p><strong>Retry is bounded, and that bound is load-bearing.</strong> Republishing inside onFailure re-enters the publish path, which attaches a fresh callback, which can fail again. Without a hard MAX_RETRIES ceiling carried in the correlation payload, a persistent failure (say, the Event Bus degradation described earlier lasting several minutes) produces an infinite publish→fail→republish loop. That loop does not just waste resources — it actively <em>consumes your callback storage budget</em>, accelerating you toward the 5 MB/30-min saturation point. The retry counter is not politeness; it is a circuit breaker.</p><p><strong>Immediate in-callback retry is the simplest option, not always the best one.</strong> Re-publishing instantly inside onFailure retries against an Event Bus that may still be degraded. For a transient-but-sustained failure like a leader-election storm, immediate retry can hammer a recovering system. A more sophisticated design defers retries — write failed events to the dead-letter object immediately and let a scheduled Apex or Queueable job replay them on a backoff schedule once the bus has had time to recover. The tradeoff is latency and complexity versus gentleness on a recovering platform. For high-stakes, high-volume streams, prefer <strong>deferred replay with backoff</strong> over <strong>immediate in-callback retry</strong>. The code above shows immediate retry for clarity; in a real high-volume system I would route everything through the dead-letter object and replay asynchronously.</p><p><strong>Partial-success DML (</strong><strong>Database.insert(records, false)) is deliberate.</strong> Inside the resilience layer, one malformed log record must never throw and abort the whole failure-handling path. Losing observability <em>and</em> the retry on account of a single bad insert is the worst outcome.</p><p><strong>Governor limits still apply, and the callback is its own transaction.</strong> The callback runs as a normal Apex transaction with normal limits — SOQL, DML, CPU, heap. If you re-query order details to repopulate event fields at retry time (the recommended pattern over storing full payloads), bulkify those queries. A naive per-UUID SOQL in a loop will hit the 100-query limit on a large failure batch. Query once with WHERE Id IN :orderIds.</p><h3>The principle underneath all of it</h3><p>The incident that opened this piece — a single degraded host cascading through backpressure, leader-election churn, synchronization storms, and timed-out payload fetches into permanent event loss — is not a Salesforce-specific story. It is the story of <em>every</em> distributed system. Slow gets mistaken for dead, recovery mechanisms amplify the problem before they resolve it, and the failure surfaces somewhere far from its cause.</p><p>What it teaches the architect is durable: <strong>a managed platform abstracts away the infrastructure, but it does not abstract away the physics.</strong> Hardware degrades. Consensus algorithms misjudge. Networks congest. Your event-driven architecture inherits all of it whether you acknowledge it or not.</p><p>Apex Publish Callbacks are the seam Salesforce gives you to <em>see</em> the failures the SaveResult hides. What you build on that seam — bounded retries, re-queryable correlation, idempotent subscribers, a monitored dead-letter store, and a budget you actively defend — is the difference between an integration that loses events in silence and one that degrades gracefully and recovers cleanly when the event bus blinks.</p><p>Assume the failure. Instrument for it. Bound your response to it. That is what resilience engineering looks like on a platform you do not control.</p><p><em>Implementation note: the cumulative 5 MB rolling-30-minute callback storage limit reflects Salesforce’s published guidance at the time of writing; the 200 MB ceiling is available only through a product exception process, not a self-service setting. Verify current allocations in the Platform Events Developer Guide against your org and API version before finalizing capacity assumptions, as platform limits evolve across releases.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69fe1262b1f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Agentforce Agent Is Stuck in a Loop. Here’s Why — and the Two Lines That Fix It]]></title>
            <link>https://medium.com/@sharmarajat1984/your-agentforce-agent-is-stuck-in-a-loop-heres-why-and-the-two-lines-that-fix-it-7157fc82b087?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7157fc82b087</guid>
            <category><![CDATA[agent-script]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentforce]]></category>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Wed, 20 May 2026 16:05:19 GMT</pubDate>
            <atom:updated>2026-05-20T16:05:19.431Z</atom:updated>
            <content:encoded><![CDATA[<p>If you build agents with Agent Script, you have probably hit this: a customer verifies their identity, everything looks fine in the variable panel, and then the agent just… spins. It bounces between your verification subagent and the router, over and over, until it gives up with a generic <em>“I apologize, but I encountered an unexpected error.”</em></p><p>I ran into exactly this last week on a customer service agent. The fix turned out to be commenting out two lines. But the <em>reason</em> those two lines cause the loop is the interesting part, and understanding it will save you from a whole category of routing bugs.</p><p>This post walks through the symptom, how to read the trace correctly, the root cause, and both the quick fix and the proper architectural fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_RgbOT0T-ZIrY2QdGqntg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnrR4X3LQQ_jZQXterf8aA.png" /></figure><h3>The symptom</h3><p>The agent had a standard structure: a start_agent router that classifies intent and hands off to specialist subagents, plus a Verify_Customers subagent that gates any sensitive action (refunds, viewing cases) behind email-code verification.</p><p>A user asked to see their cases. The router sent them to verification. They entered their email, got a code, entered the code — and the trace showed verification <em>succeeding</em>. Then the agent looped:</p><pre>Transition to Subagent: Verify Customers<br>Transition to Subagent: agent router<br>Transition to Subagent: Verify Customers<br>Transition to Subagent: agent router<br>...</pre><p>Eventually it died with the unexpected-error message.</p><p>The confusing part: the variable panel clearly showed IsVerifiedCustomer had flipped from False to True, and VerifiedCustomerId was populated with a real Contact Id. Verification worked. So why the loop?</p><h3>Reading the trace, not the variables</h3><p>The first instinct is to debug the verification action — check whether the code matched, whether the inputs were bound correctly. That is a dead end here, because the variables prove verification succeeded.</p><p>The real signal is in the <strong>Trace</strong> tab, not the Variables tab. When I expanded the failing turn, the execution order was:</p><pre>Input → Verify Customers → Reasoning → Action: Verify Code → Variables: 2 Updated<br>→ agent router → Verify Customers → agent router → ...</pre><p>Two things jumped out:</p><p>First, Verify Code ran once and succeeded (that is the &quot;2 Updated&quot; — IsVerifiedCustomer and VerifiedCustomerId). Second, and more importantly, the very next action in my verification subagent&#39;s instructions — Get_Customer_Profile — <strong>never appeared in the trace at all.</strong> The agent skipped straight from &quot;verification succeeded&quot; to bouncing between the router and verification.</p><p>That is the whole bug in one observation: the post-verification step never executed, and control got handed back to a router that immediately re-routed the user right back into verification.</p><h3>Why it loops: the classifier can’t carry state</h3><p>Here is the structure that caused it. The router was configured like this:</p><pre>start_agent agent_router:<br>    label: &quot;Agent Router&quot;<br>    description: &quot;Welcome the user and determine the appropriate subagent based on user input&quot;<br>    model_config:<br>        model: &quot;model://sfdc_ai__DefaultEinsteinHyperClassifier&quot;</pre><p>That model_config block is the culprit. It overrides which model powers the router&#39;s reasoning, and it points at the <strong>EinsteinHyperClassifier</strong> — a Salesforce-owned model purpose-built for one job: subagent classification.</p><p>According to Salesforce’s documentation, the EinsteinHyperClassifier is often used in the agent_router subagent because it offers significantly faster classification and higher accuracy for specialized classification constraints. That is genuinely useful for routing. But it comes with hard limitations that are easy to miss. The docs are explicit that this model <strong>cannot use </strong><strong>before_reasoning or </strong><strong>after_reasoning blocks, and can only call the </strong><strong>@utils.transition tool — no other tools.</strong></p><p>Read that again, because it is the entire root cause. The classifier is not a general reasoning model. It does exactly one thing: look at the current input and pick a subagent to transition to. It has no ability to reason about conversation state, run guard logic, or carry forward “this user just finished verifying, send them where they were originally headed.”</p><p>So here is what actually happened on every loop:</p><ol><li>The user verifies. Verify_Customers finishes and transitions back to the router.</li><li>The router runs the classifier. The classifier looks at the conversation, sees a refund/case intent, and classifies straight to the Order Issues subagent.</li><li>The Order Issues subagent checks IsVerifiedCustomer. On any state hiccup between turns, that check sends the user <em>back</em> to Verify_Customers.</li><li>Verify_Customers transitions back to the router.</li><li>Go to step 2.</li></ol><p>The classifier re-evaluates from scratch every single pass. It cannot remember that it just routed this person through verification, because remembering is not something a pure classifier does. It just classifies the current state, lands the user in a subagent that re-checks verification, and the cycle repeats until the runtime gives up.</p><p>The reason Get_Customer_Profile never ran is the same reason: the classifier-driven router yanked control away before the verification subagent&#39;s later steps could execute, and once the loop started, the LLM-driven reasoning that <em>would</em> have run those steps never got a turn.</p><h3>The quick fix: comment out two lines</h3><p>The fastest way to break the loop is to stop pinning the router to the classifier:</p><pre>start_agent agent_router:<br>    label: &quot;Agent Router&quot;<br>    description: &quot;Welcome the user and determine the appropriate subagent based on user input&quot;<br>    #model_config:<br>        #model: &quot;model://sfdc_ai__DefaultEinsteinHyperClassifier&quot;</pre><p>Comment those two lines out, and the router falls back to your org’s default reasoning model — a full LLM rather than a narrow classifier. That model <em>can</em> hold context across the transition. When a verified user comes back through the router, it reasons about where they were going instead of blindly re-classifying them into a subagent that bounces them back to verification. The loop disappears, and Get_Customer_Profile finally runs.</p><p>This is a completely valid fix, and for a demo, a proof of concept, or a low-volume agent, it is the right call. Routing quality goes up and the bug is gone.</p><h3>The tradeoff you just made</h3><p>Nothing is free. By removing the classifier, you traded a fast, cheap, single-purpose model for a full reasoning model on every routing decision. That means higher token cost and more latency per turn compared to the dedicated classifier. For a handful of test conversations this is irrelevant. At production scale, across thousands of sessions a day, you would feel it.</p><p>So if you want the speed and cost benefit of the classifier back, the comment-out fix is not the end state. You want to remove the <em>reason the loop happens</em>, not the classifier itself.</p><h3>The proper fix: don’t route verified users back through the router</h3><p>The architectural problem is that a verified user is being sent back to a global classifier that gets to re-decide their fate. The cleaner pattern is to never give the classifier a second crack at a user who is mid-flow.</p><p>Two ways to do this, both supported by Agent Script’s routing patterns:</p><p><strong>Option 1 — Transition directly to the destination subagent.</strong> Instead of having Verify_Customers hand control back to the router after success, have it transition straight to the subagent the user was originally headed for. Capture the originating intent before you send the user into verification, then route them back to that specific subagent once IsVerifiedCustomer == True. The classifier never re-evaluates them, so the loop is structurally impossible.</p><p><strong>Option 2 — Verify inline.</strong> Rather than treating verification as a separate hop that requires a round trip through the router, embed the verification gate inside the subagent that needs it. The user verifies and continues in the same subagent without ever leaving it. Salesforce documents this as the Required Subagent Workflow pattern: for critical routing decisions, use conditional transitions in your instructions instead of relying on the model to choose the right flow.</p><p>Either approach lets you keep the EinsteinHyperClassifier on the router for genuine first-time intent classification — where its speed and accuracy are exactly what you want — while ensuring that users already in a flow are never thrown back into the classification lottery.</p><p>NOTE : This all depends upon your use case.</p><h3>Takeaways</h3><p>A few things worth internalizing from this one:</p><p>The variable panel tells you <em>what</em> the state is; the trace tells you <em>what executed</em>. When an agent misbehaves despite correct-looking variables, read the trace and look for the step that should have run but didn’t. In my case, the missing Get_Customer_Profile was the entire diagnosis.</p><p>model_config is powerful but sharp. The EinsteinHyperClassifier is excellent at classification and nothing else — no pre/post reasoning hooks, only the transition tool. If your router needs to do anything stateful, the classifier will fight you, and the symptom is usually a routing loop.</p><p>Commenting out two lines is a legitimate fix, but know what you traded for it. You swapped a fast classifier for a full reasoning model. If cost and latency matter, fix the architecture so verified users bypass the router instead, and keep the classifier for what it is good at.</p><p>Routing loops in Agent Script almost always come down to the same thing: a stateful decision being made by something that has no memory of state. Find that mismatch, and you have found your bug.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7157fc82b087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Agentic Enterprise Is Not a Feature Release — It’s an Architectural Reset]]></title>
            <link>https://medium.com/@sharmarajat1984/the-agentic-enterprise-is-not-a-feature-release-its-an-architectural-reset-417bd6fc93b1?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/417bd6fc93b1</guid>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Wed, 13 May 2026 18:16:41 GMT</pubDate>
            <atom:updated>2026-05-13T18:16:41.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Salesforce Agentforce changes the architecture of enterprise software, and what most companies will get wrong about it</h3><p>A few months ago, I sat in a conference room watching a vendor pitch our team on the “future of customer service.” The slide deck had agents on it. So did the next deck. And the one after that. By the end of the week, I had heard “agentic AI” used fifty different ways by fifty different people to mean fifty different things — and most of them were just chatbots in a new outfit.</p><p>That afternoon, I went back to my desk, opened Agentforce Builder, and walked through what an actual agent can do today. It read a customer’s appointment history, identified a missed-fitting issue from a free-text note, checked tire inventory at three nearby stores, drafted a re-booking message in the customer’s tone, and routed the case to a regional manager for approval — all in about forty seconds. No human touched it until the approval step.</p><p>That is not a chatbot. That is a runtime.</p><p>And once you see it, you can’t unsee what it means for enterprise architecture.</p><p>This article is for the architects, CTOs, and platform leaders who are about to spend the next twenty-four months either embracing this shift or pretending it isn’t happening. I’ll be honest about what’s real, what’s still hype, and where most enterprises are going to faceplant. I’ve spent the last two years architecting Agentforce into a Fortune-scale retail environment, and the lessons aren’t the ones the keynote slides tell you about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*hJYIRMg9nIWSkVNPPe9TQw.png" /><figcaption>The Sixth Layer Diagram</figcaption></figure><h3>What Agentforce Actually Is (Strip the Marketing)</h3><p>Strip away the “digital labor” rhetoric and Agentforce is three things stacked on top of each other:</p><p><strong>One:</strong> A <em>reasoning engine</em> — Salesforce’s Atlas — that takes a user’s natural-language intent and produces a plan. Atlas isn’t a single LLM. It’s a modular pipeline of eight to twelve specialized models, retrieval-augmented generation, large action models, and reflection loops, sitting on Hyperforce infrastructure. Think of Atlas as the System 2 brain — the part that pauses and reasons instead of just predicting the next token.</p><p><strong>Two:</strong> A <em>grounding layer</em> — Data 360 (formerly Data Cloud) — that gives that brain access to the company’s real data. Customer profiles, transaction history, knowledge articles, unstructured documents converted to vector embeddings. Without grounding, the reasoning engine confidently hallucinates. With grounding, it answers from your reality.</p><p><strong>Three:</strong> A <em>trust and action layer</em> — the Einstein Trust Layer plus the action framework. PII masking before prompts leave Salesforce. Toxicity detection. Zero data retention contracts with model providers. And on the action side, a library of pre-built and custom actions the agent can invoke: Flows, Apex methods, MuleSoft APIs, external systems via the Model Context Protocol (MCP).</p><p>What turns this from “interesting AI demo” into “enterprise architecture inflection point” is the fourth thing that emerges when you compose those three: <strong>agents that can plan, reason, ground in your data, and execute actions across your systems — without being explicitly programmed to do so for each scenario.</strong></p><p>That’s a different shape of software than what we’ve built for the last thirty years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*jp7rI2ukl_MZ3Smecs4IPQ.png" /></figure><h3>Why Salesforce Is Betting the Company on This</h3><p>There’s a strategic move underneath the product launches that’s worth naming clearly.</p><p>For twenty-five years, CRM has been a <em>system of record</em>. You put data in, you query data out, humans make decisions, humans take actions. The platform’s job was to be the source of truth and the system humans worked through.</p><p>Agentic AI flips that. The agent becomes the worker. The platform becomes the <em>runtime</em> where digital labor and human labor collaborate. Records are no longer the point. Outcomes are.</p><p>If Salesforce is right about this — and I think they largely are — then “CRM” as a category is going to look very different in five years. The company that owns the agent runtime, the data fabric, and the trust layer owns the next era. Salesforce has spent the last eighteen months racing to own all three before Microsoft (Copilot Studio), ServiceNow (Now Assist), and a half-dozen specialized AI agent platforms can credibly compete.</p><p>This is why you see Agentforce 360, Agentforce Operations, Agentforce Voice, Agentforce Vibes, Agent Script, multi-agent orchestration, and the MCP/A2A protocol embrace landing in such rapid succession. It’s not feature velocity for its own sake. It’s a land grab for the operating model of the agentic enterprise.</p><p>The number that matters most isn’t the marketing one. It’s this: as of early 2026, Agentforce has approximately a five percent adoption rate among Salesforce’s customer base — roughly 29,000 deals and $800M in ARR. Strong revenue, but a long, long way from saturation. Salesforce knows this. The next twenty-four months are about converting that five percent into fifty.</p><p>Which means architects who understand Agentforce well <em>right now</em> are valuable in a way they will not be valuable in three years, when the patterns are commoditized.</p><h3>The Real Difference: Assistants vs. Agents</h3><p>This is where most of the discourse fails. Let me make it concrete.</p><p>A traditional AI assistant — Einstein Copilot, ChatGPT in a side panel, the various “AI for X” tools — is <em>reactive</em>. A human types a prompt. The assistant generates a response. The human evaluates and acts. The assistant has no goals of its own, no persistent state, no ability to act without explicit invocation. It is a fancier autocomplete.</p><p>An agentic system is <em>goal-seeking</em>. You give it an objective (“resolve this customer’s complaint”) and it decomposes that into steps, selects tools, takes actions, observes the results, reflects on whether it’s making progress, and adapts. It maintains context across turns. It can call other agents. It can hand off to humans when its confidence drops below a threshold. It is, in a real sense, <em>executing software</em> on your behalf.</p><p>The architectural implication: assistants are <em>features</em>. Agents are <em>systems</em>. Features bolt onto existing applications. Systems demand their own integration, observability, governance, and lifecycle.</p><p>Treating an agent like a feature is the single most common mistake I see enterprises make. They drop an agent into Service Cloud, watch it answer twenty cases, declare victory, and never realize they’ve just deployed an autonomous actor into their production environment with the same operational maturity they’d give a Lightning Web Component.</p><p>That ends badly. It ends with hallucinated promises to customers. It ends with regulatory exposure. It ends with the inevitable “why did the agent refund $40,000 last Tuesday” post-mortem.</p><h3>How Agentforce Changes Enterprise Application Architecture</h3><p>Here is where things get interesting if you build platforms for a living.</p><p>For the last decade, enterprise application architecture has been organized around five horizontal layers: infrastructure, data, integration, application, and experience. Security and operations cross-cut all of them. This is the model every architect alive learned to draw on a whiteboard.</p><p>Agentic AI doesn’t fit cleanly into any of those layers. It cuts through all of them.</p><p>A single agent execution touches infrastructure (Hyperforce containers running Atlas), data (Data 360 grounding queries pulling unified customer profiles), integration (MuleSoft API calls to SAP, MCP calls to external knowledge bases), application (Flow invocations and Apex actions), and experience (the channel the user is interacting through — chat, voice, email, Slack). And it does all of this <em>non-deterministically</em>. The same user intent on Tuesday may produce a different execution path than on Wednesday because the underlying LLM made a different planning choice.</p><p>The right mental model is that the agent is a <em>new layer</em> — call it the orchestration layer — that sits above the application layer and below the experience layer, with read/write access to everything below it. Your existing five-layer architecture doesn’t go away. It gets a sixth layer that arbitrates between human intent and system action.</p><p>For Salesforce architects specifically, this changes a half-dozen things about how we design systems:</p><p><strong>Topics become first-class architectural artifacts.</strong> A topic in Agentforce Builder is essentially a contract — what the agent is allowed to do, what context it draws on, what tools it can invoke. Topics need design review the same way an API does. Loosely scoped topics are a security and governance disaster waiting to happen.</p><p><strong>Actions need a registry, not just a folder.</strong> Every Flow, Apex method, or external API exposed as an agent action is now a piece of capability the reasoning engine can compose at runtime. Without a registry — what actions exist, what they do, what they cost, what they touch — you lose the ability to govern. Mature shops treat the action catalog with the same rigor they treat an API catalog.</p><p><strong>Data grounding becomes the new data modeling.</strong> It used to be enough to model your customer object correctly. Now you need to think about what the agent can <em>see</em> of that customer, what it can <em>infer</em>, and what it can <em>do</em> with that inference. Vector embeddings of knowledge content, retrieval policies, and grounding boundaries are part of the data architecture now.</p><p><strong>Hallucination is an SLA concern.</strong> Salesforce’s published numbers put hallucination rates between three and twenty-seven percent depending on configuration. That range is the difference between a production-grade agent and a liability. Reflection modules, validators, structured memory access, and out-of-the-loop transfer-to-human patterns are not nice-to-haves. They’re load-bearing.</p><h3>A Story from the Field</h3><p>A few months into our Agentforce work at the retailer where I lead the Salesforce practice, we hit a wall I didn’t expect.</p><p>We had a Customer Care use case that looked perfect on paper: agent answers common questions, looks up appointment history, reschedules when needed, escalates to a human when not. Classic. We built it in Agentforce Builder in a week. Demos went well.</p><p>Then we ran it against real production traffic in a controlled pilot.</p><p>The agent worked. But it kept making <em>one</em> class of mistake — confidently telling customers that a service was available at a store when, in fact, the store didn’t have the required equipment that week. The agent had access to the appointment system. It did not have access to the real-time equipment-availability feed, which lived in a different system entirely and had never been part of the agent’s grounding context.</p><p>The fix wasn’t in Agentforce. The fix was in our integration architecture. We had to design a new event-driven flow that surfaced equipment availability into Data 360 in near-real-time, so the agent’s grounding queries could see it.</p><p>What I took away from that: <strong>Agentforce exposes every weakness in your data and integration architecture, instantly and at scale.</strong> If your customer data is fragmented across seven systems, the agent will tell different customers different things based on which slice of truth it happened to retrieve. If your knowledge base is full of articles last updated in 2021, the agent will confidently cite 2021 policy. The reasoning engine is only as good as what it can ground in.</p><p>This is the most under-discussed reality of the Agentic Enterprise: most companies are not architecturally ready for agents because their <em>data fabric</em> isn’t ready. The work isn’t building agents. The work is fixing twenty years of accumulated data debt so that agents have something trustworthy to reason over.</p><h3>Real-World Use Cases That Actually Work</h3><p>Setting aside the demo-ware, here are the patterns I see consistently producing real value:</p><p><strong>Tier-1 and Tier-2 customer service deflection</strong> is the obvious win. Reddit, an early enterprise adopter, deflected 46% of support cases and cut resolution times by 84% — from 8.9 minutes to 1.4 minutes. Adecco handled 51% of candidate conversations outside of business hours.</p><p><strong>Sales intelligence and account research</strong> is quieter but more strategic. Agentforce’s account-management agent can produce a fresh, synthesized briefing on a customer before a meeting in seconds, pulling from CRM, third-party signals, and prior conversation data. Reps stop spending two hours prepping for a thirty-minute meeting.</p><p><strong>Back-office process automation</strong> is the sleeper. Agentforce Operations (launched April 2026, built on the Regrello acquisition) targets the unsexy work where most enterprise drag actually lives — invoice auditing, vendor onboarding, PO rescheduling, loan underwriting workflows. Early customers report cycle-time reductions of up to 70% and elimination of as much as 80% of manual back-office work.</p><p><strong>Field service dispatching</strong> is where I see Agentforce + traditional Salesforce Field Service create something genuinely new. The new Scheduling Console pairs live appointment data with AI-surfaced technician matching for emergency jobs. For retailers and service organizations with hundreds or thousands of locations, this is meaningful operating leverage.</p><p><strong>Multi-agent orchestration</strong> is the frontier. The architectural pattern Salesforce documents — a Supervisor agent acting as the front door, delegating to specialist agents within a Single-Org Multi-Agent (SOMA) topology — is the one I see maturing fastest. A customer message mentioning both billing and a product complaint gets parsed by the supervisor and split to a Finance Agent and a Product Feedback Agent simultaneously, with results recomposed before response. This works <em>today</em>.</p><p>The use cases that consistently disappoint? Anything where the business process itself is broken. Agentforce will not fix bad data, fragmented systems, undocumented policies, or organizational dysfunction. It will amplify all of them.</p><h3>The Governance Reality No One Wants to Discuss</h3><p>Here is the part of the article that won’t make Salesforce’s marketing team happy.</p><p>The Einstein Trust Layer is real and necessary. PII masking, prompt-injection defense, zero-retention contracts with model providers — all of these are genuinely important and well-built. I rely on them daily.</p><p>But trust is not a checkbox. It is an operating discipline. And the trust layer addresses maybe forty percent of the actual governance surface area you need to cover.</p><p>The other sixty percent is on you:</p><p><em>Who is accountable when an agent makes a wrong call?</em> The current legal and regulatory consensus is “the company deploying the agent.” Not the model provider, not Salesforce, not the integrator. You.</p><p><em>How do you audit a non-deterministic system?</em> Traditional change management assumes that the same input produces the same output. Agentic systems don’t. Your audit story needs to evolve from “we tested this code path” to “we monitored these behavioral patterns across N executions and they remained within tolerance.” This is closer to how you’d govern a quantitative trading system than how you’d govern a CRM customization.</p><p><em>Where is the kill switch?</em> When an agent starts doing something it shouldn’t — and at some point yours will — how fast can you disable it, and what happens to in-flight conversations? Most implementations I review have no documented answer to this.</p><p><em>What is the human-in-the-loop policy for each agent?</em> Not in general — for each one. Confidence thresholds, escalation triggers, override paths, audit trails. The agents that survive enterprise scrutiny have these designed in from day one. The ones that don’t get pulled from production after the first incident.</p><p><em>Cost governance.</em> This is sneakier than it sounds. Flex Credits billing at roughly $0.10 per action sounds trivial until you have a poorly designed agent looping through thousands of unnecessary tool calls because the reasoning engine got into a bad state. I have seen six-figure monthly bills accumulate from a single misconfigured agent inside a single weekend.</p><p>The maturity gap between organizations that have figured this out and ones that haven’t is enormous, and growing.</p><h3>What This Means for the Salesforce Architect</h3><p>If you are a Salesforce architect reading this, your job description is changing whether you signed up for it or not.</p><p>The technical skills that mattered five years ago — deep Apex, sharing model mastery, integration patterns, large-data-volume optimization — still matter. They are necessary but no longer sufficient.</p><p>The new skills are: agent design (topics, instructions, guardrails, action catalogs), prompt and grounding engineering, RAG architecture, multi-agent orchestration patterns, evaluation and observability for non-deterministic systems, and a mental model of AI governance that draws as much from security and compliance disciplines as it does from software engineering.</p><p>The architects who will thrive in the next five years are the ones who become fluent in <em>both</em> the deterministic and non-deterministic halves of the platform. You need to know when to reach for Apex and when to reach for an agent. When to design a Flow and when to define a topic. When the right answer is a hard-coded business rule and when the right answer is a constrained reasoning loop.</p><p>There is also a real career observation to share: the salary premium for Agentforce and Data Cloud skills is running 15–20% over baseline Salesforce architect compensation as of early 2026. That premium will compress over time. The window to position yourself as the person who can stand up an enterprise’s agentic practice — not just configure one — is open right now and will start closing in twelve to eighteen months.</p><h3>The Contrarian Close: Most Enterprises Will Get This Wrong</h3><p>I’ll end with the thing I most want architects and CTOs to hear, because I do not think it is being said clearly enough.</p><p><strong>Most enterprise Agentforce implementations over the next two years will fail.</strong> Not because the technology is bad — it is genuinely impressive — but because organizations will repeat the same mistakes they made with chatbots, with RPA, with prior automation waves: treating a strategic capability as a tactical project.</p><p>The pattern goes like this. An executive sees an Agentforce demo. They mandate adoption. A team is assembled. They pick a flashy use case. They build an agent in three weeks. They demo it. It works in the demo. It gets deployed. It runs for six weeks. The hallucination rate is higher than expected, the integration is brittle, the governance is hand-waved, costs are higher than modeled, and the value story is unclear. The project gets quietly de-scoped. The executive moves on to the next mandate. The architecture team is left with a half-working agent and a lot of accumulated technical debt.</p><p>The few enterprises that get this right will do five things differently.</p><p><strong>One,</strong> they will treat the agent runtime as a platform investment, not a project. They will stand up a Center of Excellence with clear charter, governance, and funding before they build a single production agent.</p><p><strong>Two,</strong> they will fix their data fabric before they fix anything else. Unified customer profiles in Data 360. Knowledge articles cleaned and embedded. Integration patterns rationalized so the agent has consistent, trustworthy ground truth.</p><p><strong>Three,</strong> they will design for the <em>whole</em> lifecycle — ideation, build, test, deploy, monitor, tune — using the Agent Development Lifecycle Salesforce has documented, not the SDLC they used for the last twenty years. Non-deterministic systems require different discipline.</p><p><strong>Four,</strong> they will instrument observability deeply from day one. Every agent execution logged to Data 360. Every action attributed. Every confidence score tracked. You cannot govern what you cannot see, and you cannot tune what you do not measure.</p><p><strong>Five,</strong> they will build with restraint. They will deploy one agent well before they deploy ten. They will favor narrow, well-bounded agents with clear human-in-the-loop checkpoints over ambitious autonomous workflows. They will earn permission to expand scope by demonstrating trustworthy behavior first.</p><p>If you do those five things, Agentforce becomes a genuine competitive advantage. If you don’t, it becomes the most expensive chatbot rollout you’ve ever paid for.</p><p>The Agentic Enterprise is coming. It is going to reshape how every Fortune 500 company runs its operations. But it is not arriving in a single product release, and it is not arriving for everyone on the same timeline. It is arriving fastest for the architects who understand that the agent is not a feature — it is the beginning of CRM becoming a runtime, not a system of record.</p><p>That distinction is the whole game.</p><h3>Key Takeaways</h3><ul><li><strong>Agentforce is not a chatbot upgrade.</strong> It is a reasoning runtime composed of Atlas (the brain), Data 360 (the grounding layer), and the Einstein Trust Layer (the guardrails), and it changes the shape of enterprise software architecture.</li><li><strong>The CRM is becoming a runtime, not a system of record.</strong> Records are no longer the point. Outcomes executed by agents collaborating with humans are the point.</li><li><strong>Agentforce exposes every weakness in your data and integration architecture instantly.</strong> The hardest work is not building agents — it is fixing the data fabric they reason over.</li><li><strong>Treating agents like features is the single most common architectural mistake.</strong> They are systems, and they need system-level governance, observability, and lifecycle.</li><li><strong>Hallucination is an SLA concern.</strong> Real production hallucination rates range from 3% to 27% depending on configuration. Plan for it.</li><li><strong>Multi-agent orchestration (SOMA, A2A, MCP) is the architectural frontier.</strong> Supervisor-plus-specialist topologies are working today and will define the next generation of enterprise applications.</li><li><strong>The salary and influence premium for Agentforce architects is real but time-limited.</strong> The window to build deep expertise is roughly twelve to eighteen months.</li><li><strong>Most enterprise Agentforce rollouts will fail.</strong> The ones that succeed will treat it as a platform investment, fix their data first, instrument observability deeply, and deploy with restraint.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417bd6fc93b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert Multi-Select Picklist Output into a Comma-Separated Collection in Salesforce Flow]]></title>
            <link>https://medium.com/@sharmarajat1984/convert-multi-select-picklist-output-into-a-comma-separated-collection-in-salesforce-flow-124b624e5734?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/124b624e5734</guid>
            <category><![CDATA[multi-selection]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-flow]]></category>
            <category><![CDATA[low-code]]></category>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 22:05:45 GMT</pubDate>
            <atom:updated>2025-11-12T22:05:45.928Z</atom:updated>
            <content:encoded><![CDATA[<p>When you work with <strong>Multi-Select Picklists</strong> in Salesforce, their values are stored as a single <strong>semicolon (;) separated string</strong> — for example:</p><pre>Option1;Option2;Option3</pre><p>While this works fine for displaying values, it becomes a challenge if you want to:</p><ul><li>Use these values in <strong>SOQL queries</strong></li><li>Loop through them in <strong>Flow</strong></li><li>Pass them to <strong>Apex or Subflows</strong></li></ul><p>To solve this, we can build an <strong>Autolaunched Flow</strong> that converts a semicolon-separated string into a <strong>collection variable</strong>. This makes it easy to use the selected values in queries and logic automation.</p><h3>Debug Flow with input and Output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEKyNCZK7bWiVYIK9_i0Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cU6FtWmA5s5F_jMEdBx8iw.png" /><figcaption>Input variable passed from the other flow to the variable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAGsxtxbCYY8o2GQJjFV5w.png" /><figcaption>Output variable from the flow — varStringCollection</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxJWAhRMtz44FdknghZ2Nw.png" /></figure><h3>Flow</h3><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;Flow xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br>    &lt;apiVersion&gt;63.0&lt;/apiVersion&gt;<br>    &lt;areMetricsLoggedToDataCloud&gt;false&lt;/areMetricsLoggedToDataCloud&gt;<br>    &lt;assignments&gt;<br>        &lt;name&gt;set020&lt;/name&gt;<br>        &lt;label&gt;set020 Process String&lt;/label&gt;<br>        &lt;locationX&gt;50&lt;/locationX&gt;<br>        &lt;locationY&gt;242&lt;/locationY&gt;<br>        &lt;assignmentItems&gt;<br>            &lt;assignToReference&gt;varStringCollection&lt;/assignToReference&gt;<br>            &lt;operator&gt;Add&lt;/operator&gt;<br>            &lt;value&gt;<br>                &lt;elementReference&gt;frmGetFirstItem&lt;/elementReference&gt;<br>            &lt;/value&gt;<br>        &lt;/assignmentItems&gt;<br>        &lt;assignmentItems&gt;<br>            &lt;assignToReference&gt;varInputString&lt;/assignToReference&gt;<br>            &lt;operator&gt;Assign&lt;/operator&gt;<br>            &lt;value&gt;<br>                &lt;elementReference&gt;frmRemoveFirstItem&lt;/elementReference&gt;<br>            &lt;/value&gt;<br>        &lt;/assignmentItems&gt;<br>        &lt;connector&gt;<br>            &lt;isGoTo&gt;true&lt;/isGoTo&gt;<br>            &lt;targetReference&gt;if010&lt;/targetReference&gt;<br>        &lt;/connector&gt;<br>    &lt;/assignments&gt;<br>    &lt;assignments&gt;<br>        &lt;name&gt;set030&lt;/name&gt;<br>        &lt;label&gt;set030 Add Final String&lt;/label&gt;<br>        &lt;locationX&gt;314&lt;/locationX&gt;<br>        &lt;locationY&gt;242&lt;/locationY&gt;<br>        &lt;assignmentItems&gt;<br>            &lt;assignToReference&gt;varStringCollection&lt;/assignToReference&gt;<br>            &lt;operator&gt;Add&lt;/operator&gt;<br>            &lt;value&gt;<br>                &lt;elementReference&gt;varInputString&lt;/elementReference&gt;<br>            &lt;/value&gt;<br>        &lt;/assignmentItems&gt;<br>    &lt;/assignments&gt;<br>    &lt;constants&gt;<br>        &lt;name&gt;SEMI_COLON&lt;/name&gt;<br>        &lt;dataType&gt;String&lt;/dataType&gt;<br>        &lt;value&gt;<br>            &lt;stringValue&gt;;&lt;/stringValue&gt;<br>        &lt;/value&gt;<br>    &lt;/constants&gt;<br>    &lt;decisions&gt;<br>        &lt;name&gt;if010&lt;/name&gt;<br>        &lt;label&gt;if010 Are there more values?&lt;/label&gt;<br>        &lt;locationX&gt;182&lt;/locationX&gt;<br>        &lt;locationY&gt;134&lt;/locationY&gt;<br>        &lt;defaultConnector&gt;<br>            &lt;targetReference&gt;set030&lt;/targetReference&gt;<br>        &lt;/defaultConnector&gt;<br>        &lt;defaultConnectorLabel&gt;No More Items&lt;/defaultConnectorLabel&gt;<br>        &lt;rules&gt;<br>            &lt;name&gt;More_Items&lt;/name&gt;<br>            &lt;conditionLogic&gt;and&lt;/conditionLogic&gt;<br>            &lt;conditions&gt;<br>                &lt;leftValueReference&gt;varInputString&lt;/leftValueReference&gt;<br>                &lt;operator&gt;Contains&lt;/operator&gt;<br>                &lt;rightValue&gt;<br>                    &lt;elementReference&gt;SEMI_COLON&lt;/elementReference&gt;<br>                &lt;/rightValue&gt;<br>            &lt;/conditions&gt;<br>            &lt;connector&gt;<br>                &lt;targetReference&gt;set020&lt;/targetReference&gt;<br>            &lt;/connector&gt;<br>            &lt;label&gt;More Items&lt;/label&gt;<br>        &lt;/rules&gt;<br>    &lt;/decisions&gt;<br>    &lt;environments&gt;Default&lt;/environments&gt;<br>    &lt;formulas&gt;<br>        &lt;description&gt;The position of the first ; in the string&lt;/description&gt;<br>        &lt;name&gt;frmFindSemiColon&lt;/name&gt;<br>        &lt;dataType&gt;Number&lt;/dataType&gt;<br>        &lt;expression&gt;FIND(&amp;quot;;&amp;quot;,{!varInputString}) - 1&lt;/expression&gt;<br>        &lt;scale&gt;0&lt;/scale&gt;<br>    &lt;/formulas&gt;<br>    &lt;formulas&gt;<br>        &lt;name&gt;frmGetFirstItem&lt;/name&gt;<br>        &lt;dataType&gt;String&lt;/dataType&gt;<br>        &lt;expression&gt;TRIM(LEFT({!varInputString}, FIND(&amp;quot;;&amp;quot;,{!varInputString}) - 1))&lt;/expression&gt;<br>    &lt;/formulas&gt;<br>    &lt;formulas&gt;<br>        &lt;name&gt;frmRemoveFirstItem&lt;/name&gt;<br>        &lt;dataType&gt;String&lt;/dataType&gt;<br>        &lt;expression&gt;TRIM(SUBSTITUTE({!varInputString},{!frmGetFirstItem}+&amp;quot;;&amp;quot;,&amp;quot;&amp;quot;))&lt;/expression&gt;<br>    &lt;/formulas&gt;<br>    &lt;interviewLabel&gt;Convert Multi-Select to Collection Subflow {!$Flow.CurrentDateTime}&lt;/interviewLabel&gt;<br>    &lt;label&gt;Convert Multi-Select to Collection Subflow&lt;/label&gt;<br>    &lt;processMetadataValues&gt;<br>        &lt;name&gt;BuilderType&lt;/name&gt;<br>        &lt;value&gt;<br>            &lt;stringValue&gt;LightningFlowBuilder&lt;/stringValue&gt;<br>        &lt;/value&gt;<br>    &lt;/processMetadataValues&gt;<br>    &lt;processMetadataValues&gt;<br>        &lt;name&gt;CanvasMode&lt;/name&gt;<br>        &lt;value&gt;<br>            &lt;stringValue&gt;AUTO_LAYOUT_CANVAS&lt;/stringValue&gt;<br>        &lt;/value&gt;<br>    &lt;/processMetadataValues&gt;<br>    &lt;processMetadataValues&gt;<br>        &lt;name&gt;OriginBuilderType&lt;/name&gt;<br>        &lt;value&gt;<br>            &lt;stringValue&gt;LightningFlowBuilder&lt;/stringValue&gt;<br>        &lt;/value&gt;<br>    &lt;/processMetadataValues&gt;<br>    &lt;processType&gt;AutoLaunchedFlow&lt;/processType&gt;<br>    &lt;start&gt;<br>        &lt;locationX&gt;56&lt;/locationX&gt;<br>        &lt;locationY&gt;0&lt;/locationY&gt;<br>        &lt;connector&gt;<br>            &lt;targetReference&gt;if010&lt;/targetReference&gt;<br>        &lt;/connector&gt;<br>    &lt;/start&gt;<br>    &lt;status&gt;Active&lt;/status&gt;<br>    &lt;variables&gt;<br>        &lt;name&gt;varInputString&lt;/name&gt;<br>        &lt;dataType&gt;String&lt;/dataType&gt;<br>        &lt;isCollection&gt;false&lt;/isCollection&gt;<br>        &lt;isInput&gt;true&lt;/isInput&gt;<br>        &lt;isOutput&gt;false&lt;/isOutput&gt;<br>        &lt;value&gt;<br>            &lt;stringValue&gt;&lt;/stringValue&gt;<br>        &lt;/value&gt;<br>    &lt;/variables&gt;<br>    &lt;variables&gt;<br>        &lt;name&gt;varStringCollection&lt;/name&gt;<br>        &lt;dataType&gt;String&lt;/dataType&gt;<br>        &lt;isCollection&gt;true&lt;/isCollection&gt;<br>        &lt;isInput&gt;false&lt;/isInput&gt;<br>        &lt;isOutput&gt;true&lt;/isOutput&gt;<br>    &lt;/variables&gt;<br>&lt;/Flow&gt;</pre><h3>Flow Overview</h3><p><strong>Flow Name:</strong> Convert Multi-Select to Collection Subflow<br> <strong>Type:</strong> Autolaunched Flow<br> <strong>Purpose:</strong> Split a semicolon-separated string (e.g., from a Multi-Select Picklist) into a <strong>String Collection variable</strong>.</p><h3>⚙️ Input and Output Variables</h3><p>Variable NameTypeDirectionDescriptionvarInputStringStringInputThe semicolon-separated string (e.g., “A;B;C”)varStringCollectionText CollectionOutputCollection of the individual values (“A”, “B”, “C”)</p><h3>Flow Logic</h3><ol><li><strong>Start</strong> → Receives the varInputString (like Multi-Input1; Multi-Input2; Multi-Input3).</li><li><strong>Decision (if010 — Are there more values?)</strong><br> Checks if the string still contains a ;.</li></ol><p>If <strong>Yes</strong> → Go to set020 Process String</p><p>If <strong>No</strong> → Go to set030 Add Final String</p><p><strong>3. Assignment (set020 Process String)</strong></p><p>Adds the first item before ; to the collection (varStringCollection)</p><p>Removes that first item from the string using formulas.</p><p><strong>4. Assignment (set030 Add Final String)</strong><br> Adds the final remaining value to the collection.</p><h3>Formula Variable</h3><p>SEMI_COLON Constant to represent delimiter ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_p0T6nDId3WToVp65aGSA.png" /><figcaption>frmGetFirstItem Get the first item before ; TRIM(LEFT({!varInputString}, FIND(&quot;;&quot;, {!varInputString}) - 1))</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRbuUrwgKcUoXlMxV0tImw.png" /><figcaption>frmRemoveFirstItem Remove the first item from the string TRIM(SUBSTITUTE({!varInputString}, {!frmGetFirstItem} + &quot;;&quot;, &quot;&quot;))</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhJJ49YtPJfn_Kp1b4xFDg.png" /><figcaption>frmFindSemiColon</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=124b624e5734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Case: LWC DataTable — Lazy Loading Contacts with Alphabet-Based Filtering in Salesforce]]></title>
            <link>https://medium.com/@sharmarajat1984/use-case-lwc-lazy-loading-contacts-with-alphabet-based-filtering-in-salesforce-66df7e527804?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/66df7e527804</guid>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 17:40:37 GMT</pubDate>
            <atom:updated>2025-11-04T16:30:17.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>When working with large datasets such as Contacts in Salesforce, loading thousands of records at once can degrade performance and slow down the user experience. To solve this, we can use <strong>lazy loading</strong> — a technique that loads data on demand as the user scrolls or interacts with the page.</p><p>In this use case, we extend lazy loading by adding an <strong>alphabet-based filter menu</strong> that allows users to load Contacts starting with a specific letter (A–Z). This approach combines performance optimization with an intuitive, user-friendly interface.</p><h3>Problem Statement</h3><p>The traditional way of displaying all Contacts at once results in:</p><ul><li>Long page load times</li><li>Increased server load due to large SOQL queries</li><li>Poor user experience on mobile or slower networks</li></ul><p>The goal is to build a dynamic Contact Directory that fetches and renders Contacts efficiently while allowing users to navigate alphabetically.</p><h3>Functional Requirements</h3><p><strong>Initial Load:</strong><br> When the component loads, it should only fetch the first batch of Contacts (for example, 20 records).</p><p><strong>Lazy Loading on Scroll:</strong><br> As the user scrolls, additional batches of Contacts should automatically load. This can be implemented using pagination logic in Apex with OFFSET and LIMIT.</p><p><strong>Alphabet Filter Menu:</strong><br> A simple A–Z menu bar allows the user to filter Contacts by their first letter. When a user clicks a letter, only those Contacts whose names start with that letter are fetched and displayed.</p><p><strong>Refresh on Filter Change:</strong><br> Selecting a new letter clears the current list and reloads data corresponding to that letter.</p><p><strong>Loading Feedback:</strong><br> A loading spinner or message should appear while new data is being fetched.</p><p><strong>No Result Message:</strong><br> If there are no Contacts for a specific letter, show a friendly message such as “No Contacts found for S”.</p><h3>Technical Design</h3><p><strong>LWC Component:</strong><br> Handles UI rendering, scroll detection, and letter-based filter selection.<br> Uses imperative Apex calls to fetch data dynamically.</p><p><strong>Apex Controller:</strong><br> Executes parameterized SOQL queries such as:</p><pre>public with sharing class Contacts {<br> @AuraEnabled(cacheable=true)<br> public static List&lt;Contact&gt; getContacts(Integer offsetSize, Integer limitSize, String firstLetter) {<br>  List&lt;Contact&gt; myContacts = new List&lt;Contact&gt;();<br>  try {<br>   if (String.isEmpty(firstLetter)) {<br>    myContacts = [<br>     SELECT Id, Name, Email, Phone<br>     FROM Contact<br>     WITH SECURITY_ENFORCED<br>     ORDER BY Name<br>     LIMIT :limitSize<br>     OFFSET :offsetSize<br>    ];<br>   } else {<br>    String filterVar = firstLetter + &#39;%&#39;;<br>    myContacts = [<br>     SELECT Id, Name, Email, Phone<br>     FROM Contact<br>     WHERE Name LIKE :filterVar<br>     WITH SECURITY_ENFORCED<br>     ORDER BY Name<br>     LIMIT :limitSize<br>     OFFSET :offsetSize<br>    ];<br>   }<br>   return myContacts;<br>  } catch (Exception e) {<br>   throw new AuraHandledException(e.getMessage());<br>  }<br> }<br>}</pre><p>Implements pagination logic to support lazy loading and filtering.</p><p><strong>Data Binding:</strong><br> Fetched data is displayed using a Lightning Data Table or a custom card layout.<br> Reactive properties ensure smooth updates as data loads.</p><h3>Benefits</h3><ul><li><strong>Improved Performance:</strong> Only a small dataset is loaded at any given time.</li><li><strong>Better User Experience:</strong> Smooth scrolling and instant access to alphabet-based filters.</li><li><strong>Scalable:</strong> Works efficiently even with tens of thousands of Contacts.</li><li><strong>Optimized SOQL Usage:</strong> Controlled pagination helps stay within governor limits.</li></ul><h3>Real-World Examples</h3><ul><li>A <strong>CRM dashboard</strong> that lets sales reps quickly browse Contacts alphabetically.</li><li>A <strong>Fleet management</strong> interface for driver or vendor contact lookup.</li><li>An <strong>internal directory</strong> for HR or operations teams to find employees by name.</li></ul><h3>Possible Enhancements</h3><ul><li>Add a <strong>search bar</strong> to combine keyword and letter filtering.</li><li>Implement <strong>client-side caching</strong> to avoid refetching already loaded data.</li><li>Include <strong>record preview</strong> or <strong>quick view modals</strong> for faster context switching.</li><li>Support <strong>infinite scroll</strong> for smoother transitions between pages.</li></ul><h3>Screen Recording</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Foe37PHuInVY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Doe37PHuInVY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Foe37PHuInVY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/56b1c6e111d4fd85b2b02525e70cabb4/href">https://medium.com/media/56b1c6e111d4fd85b2b02525e70cabb4/href</a></iframe><h3>LWC Components</h3><h4>APEX Class</h4><pre>public with sharing class Contacts {<br> @AuraEnabled(cacheable=true)<br> public static List&lt;Contact&gt; getContacts(Integer offsetSize, Integer limitSize, String firstLetter) {<br>  List&lt;Contact&gt; myContacts = new List&lt;Contact&gt;();<br>  try {<br>   if (String.isEmpty(firstLetter)) {<br>    myContacts = [<br>     SELECT Id, Name, Email, Phone<br>     FROM Contact<br>     WITH SECURITY_ENFORCED<br>     ORDER BY Name<br>     LIMIT :limitSize<br>     OFFSET :offsetSize<br>    ];<br>   } else {<br>    String filterVar = firstLetter + &#39;%&#39;;<br>    myContacts = [<br>     SELECT Id, Name, Email, Phone<br>     FROM Contact<br>     WHERE Name LIKE :filterVar<br>     WITH SECURITY_ENFORCED<br>     ORDER BY Name<br>     LIMIT :limitSize<br>     OFFSET :offsetSize<br>    ];<br>   }<br>   return myContacts;<br>  } catch (Exception e) {<br>   throw new AuraHandledException(e.getMessage());<br>  }<br> }<br>}</pre><h3>Purpose:</h3><p>This Apex class serves as a backend controller for the LWC. It fetches a list of Contact records from Salesforce in a paginated way (using OFFSET and LIMIT) and supports filtering based on the <strong>first letter</strong> of the contact’s name.</p><h3>Key Features:</h3><p><strong>Method:</strong> getContacts(Integer offsetSize, Integer limitSize, String firstLetter)</p><ul><li>Exposed as an @AuraEnabled(cacheable=true) method for use in LWC.</li><li>Returns a list of Contact records with fields: <strong>Id</strong>, <strong>Name</strong>, <strong>Email</strong>, and <strong>Phone</strong>.</li></ul><p><strong>Pagination Support:</strong></p><ul><li>Uses LIMIT and OFFSET in SOQL to load records in chunks for infinite scrolling.</li></ul><p><strong>Filtering by Initial Letter:</strong></p><ul><li>If a letter is selected, the query filters contacts whose names start with that letter (WHERE Name LIKE &#39;A%&#39;).</li></ul><p><strong>Security Enforced:</strong></p><ul><li>Uses WITH SECURITY_ENFORCED to ensure field-level and object-level security compliance.</li></ul><p><strong>Error Handling:</strong></p><p>Any exception is caught and thrown as an AuraHandledException for graceful error display in LWC.</p><h3>LWC Component</h3><p><strong><em>Note : I leave the debug statement, please make sure you remove it before prod implementation</em></strong>.</p><pre>&lt;template&gt;<br> &lt;lightning-card title=&quot;Contact Directory&quot; icon-name=&quot;utility:user&quot;&gt;<br>  &lt;lightning-button-menu slot=&quot;actions&quot; onselect={handleLetterSelect}&gt;<br>   &lt;template for:each={letters} for:item=&quot;letter&quot;&gt;<br>    &lt;lightning-menu-item label={letter} value={letter} key={letter}&gt; &lt;/lightning-menu-item&gt;<br>   &lt;/template&gt;<br>  &lt;/lightning-button-menu&gt;<br>  &lt;div class=&quot;slds-scrollable scrollerSize&quot;&gt;<br>   &lt;lightning-datatable<br>    key-field=&quot;id&quot;<br>    data={contacts}<br>    columns={columns}<br>    enable-infinite-loading<br>    onloadmore={handleLoadMore}<br>                hide-checkbox-column<br>    show-row-number-column<br>                &gt;<br>   &lt;/lightning-datatable&gt;<br>  &lt;/div&gt;<br>   &lt;template if:true={isLoading}&gt;<br>            &lt;div class=&quot;spinner-overlay&quot;&gt;<br>                &lt;lightning-spinner alternative-text=&quot;Loading...&quot; size=&quot;medium&quot;&gt;&lt;/lightning-spinner&gt;<br>            &lt;/div&gt;<br>        &lt;/template&gt; <br> &lt;/lightning-card&gt;<br>&lt;/template&gt;</pre><pre>.scrollerSize { <br> height: 500px;<br>}<br><br>.spinner-overlay {<br>    position: absolute;<br>    top: 0;<br>    left: 0;<br>    width: 100%;<br>    height: 100%;<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    background: rgba(255, 255, 255, 0.6);<br>    z-index: 10;<br>}</pre><pre>import { LightningElement, wire, api, track } from &quot;lwc&quot;;<br><br>import getContacts from &quot;@salesforce/apex/Contacts.getContacts&quot;;<br><br>const columns = [<br> { label: &quot;Name&quot;, fieldName: &quot;Name&quot;, type: &quot;text&quot; },<br> { label: &quot;Email&quot;, fieldName: &quot;Email&quot;, type: &quot;email&quot; },<br> { label: &quot;Phone&quot;, fieldName: &quot;Phone&quot;, type: &quot;phone&quot; }<br>];<br><br>export default class Challenge_contactDirectory extends LightningElement {<br> columns = columns;<br> firstLetter = &quot;&quot;;<br> letters = &quot;a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z&quot;.toUpperCase().split(&quot;,&quot;);<br> contacts = [];<br> error;<br> offset = 0;<br> limit = 20;<br><br> connectedCallback() {<br>  this.loadContacts();<br> }<br> allLoaded = false;<br> loadContacts() {<br>  if (this.allLoaded) {<br>   console.log(&quot;✅ All contacts loaded — no further Apex calls.&quot;);<br>   return;<br>  }<br><br>  return getContacts({<br>   offsetSize: this.offset,<br>   limitSize: this.limit,<br>   firstLetter: this.firstLetter<br>  })<br>   .then((result) =&gt; {<br>    let updatedRecords = [...this.contacts, ...result];<br>    if (result.length &lt; this.limit) {<br>     this.allLoaded = true;<br>    }<br>    this.contacts = updatedRecords;<br>    console.log(&quot; updatedRecords contacts &quot; + JSON.stringify(updatedRecords));<br>    this.error = undefined;<br>   })<br>   .catch((error) =&gt; {<br>    console.error(&quot;Error loading contacts:&quot;, error);<br>    this.error = error;<br>    this.contacts = undefined;<br>   });<br> }<br><br> handleLoadMore(event) {<br>  // debugger<br>  //const currentContacts = this.contacts;<br>  const { target } = event;<br>  // Prevent load if all records already loaded<br>  if (this.allLoaded) {<br>   console.log(&quot;⚠️ handleLoadMore ignored — all records loaded.&quot;);<br>   target.isLoading = false;<br>   return;<br>  }<br><br>  target.isLoading = true;<br>  this.offset = this.offset + this.limit;<br><br>  this.loadContacts().then(() =&gt; {<br>   target.isLoading = false;<br>  });<br> }<br><br> handleLetterSelect(event) {<br>  this.firstLetter = event.detail.value;<br>  this.offset = 0;<br>  this.contacts = [];<br>  this.allLoaded = false;<br>  const { target } = event;<br>  target.isLoading = true;<br>  this.loadContacts().then(() =&gt; {<br>   target.isLoading = false;<br>  });<br> }<br>}</pre><h4>Purpose:</h4><p>Displays a scrollable, dynamic <strong>Contact Directory</strong> in a Lightning Card format, supporting:</p><ul><li>Infinite loading (lazy loading)</li><li>Filtering by first letter</li><li>Responsive UI with a loading spinner</li></ul><p><strong>1. Template (HTML):</strong></p><p><strong><em>What It Does:</em></strong></p><ul><li>Displays contacts in a <strong>lightning-datatable</strong> inside a scrollable area.</li><li>Uses a <strong>lightning-button-menu</strong> for selecting a letter to filter contacts.</li><li>Includes a <strong>spinner overlay</strong> to show loading progress.</li></ul><h4>Key Elements:</h4><ul><li>&lt;lightning-card&gt;: Provides a structured card layout with title and icon.</li><li>&lt;lightning-button-menu&gt;: Displays an A–Z menu; selecting a letter triggers filtering.</li><li>&lt;lightning-datatable&gt;: Renders the list of contacts dynamically with infinite scrolling.</li><li>&lt;lightning-spinner&gt;: Visually indicates when data is loading.</li></ul><h4>Custom Styles:</h4><ul><li>.scrollerSize: Restricts datatable height for scrollable view.</li><li>.spinner-overlay: Creates a transparent overlay spinner during loading operations.</li></ul><p><strong>2. JavaScript (Controller Logic):</strong></p><p><strong><em>What It Does:</em></strong></p><p>Handles the <strong>data loading</strong>, <strong>filtering</strong>, and <strong>infinite scroll logic</strong> by interacting with the Apex method.</p><p>Key Properties:</p><ul><li>columns: Defines the structure of the datatable (Name, Email, Phone).</li><li>letters: A–Z array for filtering menu.</li><li>contacts: Holds currently loaded contact records.</li><li>offset, limit: Used to control pagination (default 20 records per batch).</li><li>firstLetter: Stores the selected letter filter value.</li><li>allLoaded: Boolean flag to prevent unnecessary Apex calls once all data is loaded.</li><li>isLoading: Used for showing the spinner overlay.</li></ul><p><strong>Core Methods:</strong></p><p><strong>connectedCallback()</strong></p><ul><li>Loads the initial batch of contacts when the component is first rendered.</li></ul><p><strong>loadContacts()</strong></p><ul><li>Calls the Apex method getContacts() with current offset, limit, and filter.</li><li>Appends results to existing list for continuous scrolling.</li><li>Stops loading once fewer than limit records are returned (all data loaded).</li><li>Handles both success and error cases.</li></ul><p><strong>handleLoadMore(event)</strong></p><ul><li>Triggered automatically when the datatable scroll reaches the end.</li><li>Increments offset and fetches the next batch of contacts.</li><li>Prevents loading if allLoaded is already true.</li></ul><p><strong>handleLetterSelect(event)</strong></p><ul><li>Triggered when a user selects a letter from the menu.</li><li>Resets pagination (offset=0) and clears existing contacts.</li><li>Calls loadContacts() again with the selected first letter filter.</li></ul><h3>💡 Overall Flow:</h3><p><strong>Initial Load:</strong></p><ul><li>Component loads → calls Apex → displays first 20 contacts.</li></ul><p><strong>Infinite Scrolling:</strong></p><ul><li>User scrolls → triggers handleLoadMore() → loads next batch (next 20).</li></ul><p><strong>Filtering by Letter:</strong></p><ul><li>User selects a letter (e.g., “A”) → resets offset and data → loads only contacts starting with “A”.</li></ul><p><strong>Spinner Overlay:</strong></p><ul><li>Appears while Apex data is loading for better UX feedback.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66df7e527804" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Initial Setting for VSCode/Agenforce Vibes]]></title>
            <link>https://medium.com/@sharmarajat1984/my-initial-setting-for-vscode-agenforce-vibes-b91eaf5004c0?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91eaf5004c0</guid>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 20:23:02 GMT</pubDate>
            <atom:updated>2025-10-29T20:23:02.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>1- Setup my tasks.json file under .vscode folder</h3><pre>{<br> // See https://go.microsoft.com/fwlink/?LinkId=733558<br> // for the documentation about the tasks.json format<br> &quot;version&quot;: &quot;2.0.0&quot;,<br> &quot;tasks&quot;: [{<br>  &quot;label&quot;: &quot;Push When Build&quot;,<br>  &quot;type&quot;: &quot;shell&quot;,<br>  &quot;command&quot;: &quot;sf project deploy start --json --ignore-conflicts&quot;,<br>  &quot;group&quot;: {<br>   &quot;kind&quot;: &quot;build&quot;,<br>   &quot;isDefault&quot;: true<br>  },<br>  &quot;presentation&quot;: {<br>   &quot;reveal&quot;: &quot;always&quot;,<br>   &quot;panel&quot;: &quot;dedicated&quot;,<br>   &quot;clear&quot;: true,<br>   &quot;focus&quot;: false,<br>   &quot;showReuseMessage&quot;: true<br>  }<br> }]<br>}</pre><ul><li>This task is a <strong>VS Code build task</strong> that runs a Salesforce deployment command.</li><li>It’s set as the <strong>default build task</strong>, so pressing <strong>Ctrl+Shift+B</strong> (or Cmd+Shift+B on Mac) will run it.</li><li>The <strong>terminal presentation</strong> is customized to always show output in a clean, dedicated panel without stealing focus.</li><li>You could add <strong>multiple tasks</strong> in the tasks array for other commands like sf project retrieve start, npm build, or custom shell scripts.</li></ul><h4>tasks.json Explained (Pointer Notes)</h4><ul><li><strong>&quot;version&quot;: &quot;2.0.0&quot;</strong> → Specifies the schema version for VS Code tasks.</li><li><strong>&quot;tasks&quot;</strong> → Array containing all defined tasks</li><li><strong>&quot;label&quot;: &quot;Push When Build&quot;</strong> → Friendly name for the task shown in VS Code.</li><li><strong>&quot;type&quot;: &quot;shell&quot;</strong> → Task runs in the system shell (bash, zsh, PowerShell, CMD).</li><li><strong>&quot;command&quot;: &quot;sf project deploy start --json --ignore-conflicts&quot;</strong> →</li></ul><p>sf project deploy start → Starts Salesforce project deployment.</p><p>--json → Outputs results in JSON format.</p><p>--ignore-conflicts → Ignores conflicts with other deployments.</p><ul><li><strong>&quot;group&quot;: { &quot;kind&quot;: &quot;build&quot;, &quot;isDefault&quot;: true }</strong> →</li></ul><p>Assigns the task to <strong>build tasks</strong>.</p><p>isDefault: true → Task runs by default when pressing <strong>Ctrl+Shift+B / Cmd+Shift+B</strong>.</p><ul><li><strong>&quot;presentation&quot;</strong> → Controls terminal output and behavior:</li></ul><p>reveal: &quot;always&quot; → Always shows terminal when task runs.</p><p>panel: &quot;dedicated&quot; → Uses a dedicated terminal panel.</p><p>clear: true → Clears terminal before running task.</p><p>focus: false → Does not automatically focus on terminal.</p><p>showReuseMessage: true → Shows message if terminal panel is reused.</p><h3>Setting.json under .vscode folder</h3><pre>{<br>    &quot;codeBuilder.showWelcomePage&quot;: false,<br>    &quot;explorer.compactFolders&quot;: false,<br>    &quot;editor.formatOnSave&quot;: true,<br>    &quot;workbench.editor.enablePreview&quot;: true,<br>    &quot;editor.minimap.enabled&quot;: false,<br>    &quot;xml.preferences.showSchemaDocumentationType&quot;: &quot;none&quot;,<br>    &quot;salesforce.einsteinForDevelopers.enable&quot;: true<br>}</pre><h4>settings.json Explained (Pointers)</h4><ul><li><strong>&quot;codeBuilder.showWelcomePage&quot;: false</strong></li></ul><p>Disables the <strong>welcome page</strong> when opening Code Builder / VS Code.</p><ul><li><strong>&quot;explorer.compactFolders&quot;: false</strong></li></ul><p>Shows <strong>full folder structure</strong> in the Explorer instead of collapsing single-child folders.</p><ul><li><strong>&quot;editor.formatOnSave&quot;: true</strong></li></ul><p>Automatically <strong>formats code</strong> when you save a file.</p><ul><li><strong>&quot;workbench.editor.enablePreview&quot;: true</strong></li></ul><p>Opens files in <strong>preview mode</strong> (tab reused until edited or pinned).</p><ul><li><strong>&quot;editor.minimap.enabled&quot;: false</strong></li></ul><p>Disables the <strong>code minimap</strong> on the right side of the editor</p><p><strong>&quot;xml.preferences.showSchemaDocumentationType&quot;: &quot;none&quot;</strong></p><p>Disables automatic <strong>XML schema documentation popups</strong> in XML files.</p><ul><li><strong>&quot;salesforce.einsteinForDevelopers.enable&quot;: true</strong></li></ul><p>Enables <strong>Einstein AI features</strong> for Salesforce development (code suggestions, automation).</p><h3>CreateOrg.sh under folder Script</h3><pre># Execute in Code Builder terminal using: ./EXFiles/scripts/CreateOrg.sh<br>echo &quot;*** Creating scratch Org...&quot;<br>#sf org create scratch --definition-file config/project-scratch-def.json --set-default --alias soDEX602 --duration-days 30<br>sf org create scratch --definition-file config/project-scratch-def.json --set-default --alias lwc-recipes --duration-days 30<br>echo &quot;*** Pushing metadata to scratch Org...&quot;<br>sf project deploy start<br>echo &quot;*** Assigning permission  recipes set to your user...&quot;<br>sf org assign permset -n recipes<br>echo &quot;*** Creating data&quot;<br>sf data tree import -p ./data/data-plan.json<br>sf org open</pre><p>This has bunch of comman i use to create scratch org</p><p>for execution Open Terminal ./scripts/CreateOrg.sh</p><pre>If you get an error in Terminal <br>/home/codebuilder/lwc-recipes/scripts/CreateOrg.sh: Permission denied<br><br>Run following command <br>ls -l /home/codebuilder/lwc-recipes/scripts/CreateOrg.sh<br>if you see something like<br><br>-rw-r--r-- 1 codebuilder codebuilder 1234 Oct 29 09:00 CreateOrg.sh<br><br>That means you don&#39;t have permission on this file<br><br>Run following command to change the mode<br>chmod +x /home/codebuilder/lwc-recipes/scripts/CreateOrg.sh</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91eaf5004c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC manage Subscription Via Postman— In Action]]></title>
            <link>https://medium.com/@sharmarajat1984/grpc-manage-subscription-via-postman-in-action-018e5083d7f7?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/018e5083d7f7</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[manage-subscription]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[replayid]]></category>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 01:39:10 GMT</pubDate>
            <atom:updated>2025-08-19T01:41:45.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past few weeks, I’ve been working extensively with <strong>gRPC Managed Subscriptions</strong> in Salesforce. — <strong><em>Pay it forward</em></strong>….. (one of life Lessons of Mr. Halle)</p><p>Salesforce recently introduced <strong>gRPC Managed Subscriptions</strong> as part of the Pub/Sub API capabilities. This feature is designed to simplify how we consume event messages by letting Salesforce manage subscription state, delivery, and replay under the hood — so developers don’t need to handle all the complexities of durable subscriptions themselves. Instead of constantly tracking replay IDs or worrying about event persistence, Managed Subscriptions offload that responsibility to Salesforce, which makes it much easier to build scalable, event-driven integrations.</p><p>That said, the product is still in <strong>Beta</strong>, and with that comes limited documentation, changing behavior, and a lack of community examples to learn from. While Salesforce provides some references in the official documentation and there’s a helpful <a href="https://developer.salesforce.com/blogs/2024/05/pub-sub-api-made-easy-via-managed-subscriptions">Salesforce Developer Blog post</a>, I personally found it challenging to set up a successful POC. The documentation covers the basics, but doesn’t go deep enough into the common pitfalls or real-world scenarios many teams will face.</p><p>As part of my own work, I collaborated with Salesforce Support and the product team to troubleshoot and experiment, eventually arriving at a working approach. In this post, I’ll walk through those challenges, the solutions I discovered, and some best practices for anyone looking to explore <strong>gRPC Managed Subscriptions in Salesforce Pub/Sub API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AnRn4UM6fWDHRxrb.jpeg" /></figure><h3><strong>Pre-Requisite</strong></h3><p>Before setting up a <strong>gRPC Managed Subscription</strong>, make sure you have the following in place. You can refer back to my earlier posts for detailed steps:</p><p><a href="https://medium.com/@sharmarajat1984/salesforce-pub-sub-api-grpc-via-postman-and-decode-the-payload-823063be6cd7">Salesforce Pub/Sub API via Postman &amp; Decode the Payload</a></p><p><a href="https://medium.com/@sharmarajat1984/oauth-in-salesforce-via-postman-example-f78c81f4cb7b?source=your_stories_page--------------------------------------------">OAuth in Salesforce via Postman</a></p><h4>Setup Checklist</h4><ol><li><strong>Connected App</strong> — Create a Connected App in Salesforce so Postman (or any client) can call APIs on your org.</li><li><strong>Platform Event</strong> — Define a Platform Event. (In this post, I’ll reuse the same Platform Event I created in my previous blog).</li><li><strong>OAuth Access Token</strong> — Generate an OAuth 2.0 access token using any of the methods described in my OAuth blog above.</li></ol><h3>Create Subscription</h3><p>Thanks to <a href="https://developer.salesforce.com/blogs/2024/05/pub-sub-api-made-easy-via-managed-subscriptions">blog</a> that help me to create a subscription.</p><p>I have used PostMan to create a Subscriptions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4mZ08-kEyE8mEXxrCCZvw.png" /></figure><pre>{<br>  &quot;FullName&quot;: &quot;My_Managed_Subscription&quot;,<br>  &quot;Metadata&quot;:<br>  {<br>      &quot;label&quot; : &quot;My Managed Subscription&quot;,<br>      &quot;topicName&quot; : &quot;/event/MediumBlog__e&quot;,<br>      &quot;defaultReplay&quot;: &quot;LATEST&quot;,<br>      &quot;state&quot; : &quot;RUN&quot;,<br>      &quot;errorRecoveryReplay&quot; : &quot;LATEST&quot;<br>  }<br>}</pre><p>Save the Response as it contain the <strong><em>SubscriptionId</em></strong> which you need later in the reques</p><p>This JSON payload defines a <strong>Managed Subscription</strong> in Salesforce. The FullName field specifies the unique developer name for the subscription, while the Metadata section contains its configuration. The label is a human-readable name for the subscription, and topicName indicates the event channel it subscribes to—in this case, the custom Platform Event /event/MediumBlog__e. The defaultReplay determines where the subscription starts consuming events when first created, with LATEST meaning it only receives new events. The state field sets the subscription to RUN, making it active and ready to deliver events, while errorRecoveryReplay defines from where to resume if an error occurs, with LATEST ensuring it picks up from the most recent events. Together, these fields define <strong>what to subscribe to, how events are replayed, and whether the subscription is active</strong>, allowing Salesforce to manage event delivery automatically.</p><p>You can pull the metadata via VS</p><pre>    &lt;types&gt;<br>        &lt;members&gt;*&lt;/members&gt;<br>        &lt;name&gt;ManagedEventSubscription&lt;/name&gt;<br>    &lt;/types&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhnQvKSFHQt62OeY8CNijA.png" /></figure><p>OR Run SQL</p><pre>SELECT Id,DeveloperName,FullName<br>FROM ManagedEventSubscription  LIMIT 200</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUsbOyRMLDhVXQzVCfxAag.png" /><figcaption>Id — used in later gRPC API Call</figcaption></figure><h3>Subscribe to PE via ManageSubscription gRPC API</h3><p>As discussed in previous <a href="https://medium.com/@sharmarajat1984/salesforce-pub-sub-api-grpc-via-postman-and-decode-the-payload-823063be6cd7?source=your_stories_page--------------------------------------------">blog</a> — Please create a new request and populate accessToken, instanceURL, tenantid attribute under Metadata tab.</p><p>Use Operation as PubSub/ManageSubscribe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSLgMwtsa1pKE8YVCtOCGg.png" /></figure><p>In your first Request, We pass the subscription_id and num_requested — like how many messages i want to read in 1 request.</p><pre>{<br>    &quot;subscription_id&quot; : &quot;18xbm000001MojxAAC&quot;,<br>    &quot;num_requested&quot;: 100<br>}</pre><p>Click on Invoke and then Send</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voG_bJ5nvz6uin-8OqMHKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCHRW-tm1pQW-dcKjO_8Bg.png" /></figure><p>Go to your VSCode or Developer Console and Publish some messages and sametime check in PostMan you are going to receive 4 messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSxCp8sTsNuDWmJY6Qq_kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-vurVsHG3j0aQ-F4ZWqJA.png" /><figcaption>6Pum/pdmJDAwNWJtMDAwMDBFcE1zckFBRgJcV2VsY29tZSB0byBSYWphdCBwb3N0IGRlbW8gZm9yIGdSUEMgbWVzc2FnZSAwNA==</figcaption></figure><p>Use my previous <a href="https://medium.com/@sharmarajat1984/salesforce-pub-sub-api-grpc-via-postman-and-decode-the-payload-823063be6cd7?source=your_stories_page--------------------------------------------">blog</a> — and decode the last message. — which is 6Pum/pdmJDAwNWJtMDAwMDBFcE1zckFBRgJcV2VsY29tZSB0byBSYWphdCBwb3N0IGRlbW8gZm9yIGdSUEMgbWVzc2FnZSAwNA==</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtgv7MmR0SDcBE6iBtbsWA.png" /></figure><p>Now, Here is the magic we don’t close the POSTMan window (Technically using the same client) and send a comitt request to tell that we successfully read the last message.</p><p>Commit_replay_id_request node with the request_id and last successful read replay_id.</p><p>Click Send —</p><pre>{<br>    &quot;subscription_id&quot; : &quot;18xbm000001MojxAAC&quot;,<br>    &quot;num_requested&quot;: 100,<br>    &quot;commit_replay_id_request&quot;: {<br>    &quot;commit_request_id&quot;: &quot;Test  commit replay ID&quot;,<br>    &quot;replay_id&quot;: &quot;AAAAAAAAxXgAAA==&quot;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAZC12Whjfz1hzwqYVViPA.png" /></figure><p>Salesforce sent back the response for succesful commit.</p><pre><br>    &quot;events&quot;: [],<br>    &quot;latest_replay_id&quot;: &quot;AAAAAAAAxXgAAA==&quot;,<br>    &quot;rpc_id&quot;: &quot;5bddf8d4-4d3a-47fb-9c34-71de38f776aa&quot;,<br>    &quot;pending_num_requested&quot;: 100,<br>    &quot;commit_response&quot;: {<br>        &quot;commit_request_id&quot;: &quot;Test  commit replay ID&quot;,<br>        &quot;replay_id&quot;: &quot;AAAAAAAAxXgAAA==&quot;,<br>        &quot;error&quot;: null,<br>        &quot;process_time&quot;: &quot;1755566803977&quot;<br>    }<br>}</pre><h4>Disconnect the Client/ Client is Down</h4><p>Now you disconnect your client by clicking on “End Stream Button”. Open up new Client but remember we need to use same SubscriptionId where we commit.</p><h4>Publish PE While connection is Closed</h4><p>I have published 4 PE similar to earlier example but my message this time as</p><pre>EventBus.publish(<br>    new MediumBlog__e (<br>        payload__c = &#39;Publishing PE while my client is closed: checking if I start the subscription again, do I get message 04&#39;<br>    )<br>);</pre><h4>Subscribe Again gRPC operation</h4><p>As we did earlier using subscriptionId, use manageSubscribe operation and you will see the magic as soon as you subscribe you will see 4 messages which was published when client was down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*toSi5v9S7uK1C4tV5f8Hyg.png" /></figure><p>If i decode the last message,</p><blockquote>uoGd/5dmJDAwNWJtMDAwMDBFcE1zckFBRgLQAVB1Ymxpc2hpbmcgUEUgd2hpbGUgbXkgY2xpZW50IGlzIGNsb3NlZDogY2hlY2tpbmcgaWYgSSBzdGFydCB0aGUgc3Vic2NyaXB0aW9uIGFnYWluLCBkbyBJIGdldCBtZXNzYWdlIDA0</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0q7ggwKN9zia1qwHyeBQKQ.png" /></figure><p>Bingooooo, success…….</p><p>But make sure you commit the last successful replay_id back :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=018e5083d7f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce Pub/Sub API — gRPC Via PostMan And Decode the payload]]></title>
            <link>https://medium.com/@sharmarajat1984/salesforce-pub-sub-api-grpc-via-postman-and-decode-the-payload-823063be6cd7?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/823063be6cd7</guid>
            <category><![CDATA[pe]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[salesforce-pubsub-api]]></category>
            <category><![CDATA[event-platform]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 21:36:20 GMT</pubDate>
            <atom:updated>2026-05-15T17:51:37.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Salesforce Pub/Sub API with Postman: A Hands-On Guide to gRPC, Avro Payloads, and Replay IDs</h3><p>Salesforce’s Pub/Sub API replaces the aging CometD streaming model with a modern, gRPC-based foundation built on HTTP/2 and Protocol Buffers. It is the recommended path for streaming Platform Events, Change Data Capture (CDC), and custom event notifications — and it is the only streaming API Salesforce is actively investing in.</p><p>For architects, the appeal goes beyond the protocol. Pub/Sub gives you flow-controlled subscriptions, durable replay across a 72-hour retention window, and a publish path that does not consume API request limits the same way REST does. For developers, it brings strongly typed payloads via Avro schemas and a single bi-directional channel for both publishing and subscribing.</p><p>The trade-off is steeper onboarding. You are now dealing with gRPC tooling, binary Avro payloads, opaque replay IDs, and schema retrieval — none of which Workbench or a browser will help you with. This post walks through the full loop in Postman, from subscription to decoded payload, then closes with the production considerations that matter when you graduate from prototype to live integration.</p><h3>What we will build</h3><ol><li>Subscribe to a custom Platform Event over gRPC using Postman.</li><li>Retrieve the Avro schema for that event.</li><li>Publish an event from Apex and consume it through the subscription.</li><li>Decode the Base64-wrapped Avro payload locally with Python.</li><li>Understand the replay ID and how to use it safely.</li></ol><h3>Prerequisites</h3><ul><li>A Salesforce org where you can create a Platform Event and a Connected App.</li><li>An OAuth access token. If you have not set this up before, see my earlier post: <a href="https://medium.com/@sharmarajat1984/oauth-in-salesforce-via-postman-example-f78c81f4cb7b">OAuth in Salesforce via Postman</a>.</li><li>Postman 10.x or later (gRPC support is built in).</li><li>Python 3.9+ for the decoding step.</li></ul><p>To grab the org details you will need throughout this guide, run:</p><p>bash</p><pre>sf org user display</pre><p>This returns your access token, instance URL, and org ID — the three values gRPC metadata will require on every call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLxbpIkLB5axMsNg4d_F1A.png" /><figcaption>This contains all the parameters you need to connect the org in following steps.</figcaption></figure><h4><strong><em>Step 1: Create the Platform Event and Connected App</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bga6JIK-45NSKjv8V5alRQ.png" /></figure><p>Create a custom Platform Event named MediumBlog__e with a single text field, payload__c. Then set up a Connected App called MediumBlogApp and enable OAuth with the scopes needed for Pub/Sub access (at minimum api and refresh_token).</p><p>If you need a refresher on Connected App setup or the OAuth flow, my earlier post linked above covers it end to end.</p><h4><strong><em>Step 2: Configure Postman for gRPC</em></strong></h4><p>Postman’s gRPC client needs three things: the endpoint, the service definition, and the auth metadata.</p><p><strong>Create the request:</strong> File → New → gRPC.</p><p><strong>Endpoint:</strong> api.pubsub.salesforce.com:7443 (TLS is required; Postman handles it automatically on port 7443).</p><p><strong>Service definition:</strong> Import the official .proto file from the <a href="https://github.com/forcedotcom/pub-sub-api">forcedotcom/pub-sub-api</a> repository. Without this, Postman cannot list the available methods. Download pubsub_api.proto and import it via Postman&#39;s service definition panel.</p><p>Once imported, you will see the available methods in the dropdown: GetTopic, GetSchema, Subscribe, Publish, PublishStream, and the managed-subscription variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXqtT8W6sN4zkMqKO9RDbw.png" /></figure><p>Auth metadata</p><p>Pub/Sub gRPC expects three metadata keys, all lowercase:</p><p>KeyValueaccesstokenOAuth access token from Step 1instanceurlMy Domain URL with https:// prefixtenantid18-character Org ID</p><p>Key names are case-sensitive in gRPC metadata. Capitalizing AccessToken will fail authentication with an unhelpful error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2rmb5nGWeyMQgQLoM0YtGg.png" /></figure><h4><strong><em>Step 3: Verify topic access with GetTopic</em></strong></h4><pre>{&quot;topic_name&quot;: &quot;/event/MediumBlog__e&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UugiZKvhm_r-79PZOMz0YQ.png" /></figure><p>Select pubsub.v1.PubSub/GetTopic from the method dropdown and send:</p><pre>{ &quot;topic_name&quot;: &quot;/event/MediumBlog__e&quot; }</pre><p>The response confirms your client can see and act on the topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmlNdX3r-n9WQLmyOFA56g.png" /></figure><pre>{<br>  &quot;topic_name&quot;: &quot;/event/MediumBlog__e&quot;,<br>  &quot;tenant_guid&quot;: &quot;core/prod/00D...&quot;,<br>  &quot;can_publish&quot;: true,<br>  &quot;can_subscribe&quot;: true,<br>  &quot;schema_id&quot;: &quot;aolrVzTrnnd-bbgecmvMKw&quot;,<br>  &quot;rpc_id&quot;: &quot;5f3a...&quot;<br>}</pre><p>Key fields:</p><ul><li><strong>schema_id</strong> — the identifier you will use in GetSchema to fetch the Avro definition needed for payload decoding.</li><li><strong>can_publish / </strong><strong>can_subscribe</strong> — driven by the Connected App&#39;s user permissions. If either is false, fix the profile or permission set before continuing.</li><li><strong>tenant_guid</strong> — Salesforce&#39;s internal tenant identifier; useful when opening a support case.</li><li><strong>rpc_id</strong> — a per-call trace ID. Capture this in your logs; it is what Salesforce support will ask for.</li></ul><blockquote><strong>schema_id</strong>: This is the identifier for the <strong>Avro schema</strong> used to serialize and deserialize event payloads. <strong><em>You’ll need this ID to retrieve the schema and decode the payload correctly</em></strong>.</blockquote><h4><strong><em>Step 4: Retrieve the Avro schema</em></strong></h4><p>Duplicate the GetTopic request (so metadata carries over) and switch the method to pubsub.v1.PubSub/GetSchema. Send the schema_id from the previous response:</p><pre>{ &quot;schema_id&quot;: &quot;aolrVzTrnnd-bbgecmvMKw&quot; }</pre><p>The response includes schema_json — the Avro schema as a JSON string:</p><pre>{<br>  &quot;type&quot;: &quot;record&quot;,<br>  &quot;name&quot;: &quot;MediumBlog__e&quot;,<br>  &quot;namespace&quot;: &quot;com.sforce.eventbus&quot;,<br>  &quot;fields&quot;: [<br>    { &quot;name&quot;: &quot;CreatedDate&quot;, &quot;type&quot;: &quot;long&quot;, &quot;doc&quot;: &quot;CreatedDate:DateTime&quot; },<br>    { &quot;name&quot;: &quot;CreatedById&quot;, &quot;type&quot;: &quot;string&quot;, &quot;doc&quot;: &quot;CreatedBy:EntityId&quot; },<br>    { &quot;name&quot;: &quot;payload__c&quot;, &quot;type&quot;: [&quot;null&quot;, &quot;string&quot;], &quot;doc&quot;: &quot;Data:Text:00Nbm00000Qicqb&quot;, &quot;default&quot;: null }<br>  ]<br>}</pre><p>A few things worth understanding here:</p><ul><li><strong>Schemas are immutable per ID.</strong> If you add a field to the Platform Event, Salesforce issues a new schema_id. Old events in the retention window remain decodable with their original schema.</li><li><strong>Cache schemas in production.</strong> Call GetSchema once per schema_id and store the result. Calling it on every event is a common mistake that burns API capacity and adds latency to your consumer.</li><li><strong>CreatedDate is epoch milliseconds.</strong> Treat it as a long, then convert when displaying.</li></ul><blockquote><strong>schema_json</strong>: This is the actual <strong>Avro schema</strong>, represented as a JSON string. It defines the structure of your event — which fields it contains, their types, and additional metadata. We need this to decode the payload.</blockquote><h4><strong><em>Step 5: Subscribe to the event stream</em></strong></h4><p>Duplicate the request again and switch to pubsub.v1.PubSub/Subscribe. The Subscribe method is a server-streaming RPC, which means Postman will keep the connection open and stream responses as events arrive.</p><p>Send this initial fetch request:</p><p>json</p><pre>{<br>  &quot;topic_name&quot;: &quot;/event/MediumBlog__e&quot;,<br>  &quot;num_requested&quot;: 100,<br>  &quot;replay_preset&quot;: &quot;LATEST&quot;<br>}</pre><p>Click <strong>Invoke</strong>, then <strong>Send</strong> to open the stream.</p><h4>Understanding num_requested</h4><p>num_requested is a <strong>credit-based flow control mechanism</strong>, not a batch size. It tells Salesforce: &quot;I am ready to receive up to 100 events.&quot; Once those credits are consumed, the stream pauses until you send another FetchRequest to replenish them. In production code, you replenish credits as you process events; in Postman, you would re-send the request when credits run out.</p><p>This is the single most common stumbling block for first-time Pub/Sub users — if your stream “stops working” after the first batch, this is why.</p><h4><strong>Replay presets</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGg5ddfQNDrsoL1sPE7xOQ.png" /></figure><p>For production resilience, you want CUSTOM with the most recent replay ID your consumer has durably persisted.</p><pre>{<br>  &quot;topic_name&quot;: &quot;/event/MediumBlog__e&quot;,<br>  &quot;num_requested&quot;: 100<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4NOQ_9Y3i2bokQV6VRsvg.png" /><figcaption><strong>Change the PubSub/Subscribe</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msgSk8OmwfV6Y0rsfyfNMQ.png" /><figcaption>Click on Send button, and in the Response you can see System is ready to Read the Message.</figcaption></figure><p>Bingoo !!!! now time is to Publish an Event.</p><h4>Step 6: Publish an event from Apex</h4><p>With the subscription open, switch to a Developer Console anonymous Apex window and publish:</p><pre>EventBus.publish(<br>    new MediumBlog__e(<br>        payload__c = &#39;Welcome to Rajat Blog on Medium 1&#39;<br>    )<br>);</pre><p>Postman should immediately show the event arriving on the open stream. The pending_num_requested counter decrements to 99, confirming the credit was consumed:</p><pre>{<br>  &quot;events&quot;: [<br>    {<br>      &quot;event&quot;: {<br>        &quot;headers&quot;: [],<br>        &quot;id&quot;: &quot;01faa11d-954b-4cbc-b275-a4c7c6fc8727&quot;,<br>        &quot;schema_id&quot;: &quot;aolrVzTrnnd-bbgecmvMKw&quot;,<br>        &quot;payload&quot;: &quot;gMrQ6vxlJDAwNWJtMDAwMDBFcE1zckFBRgJCV2VsY29tZSB0byBSYWphdCBCbG9nIG9uIE1lZGl1bSAx&quot;<br>      },<br>      &quot;replay_id&quot;: &quot;AAAAAAAAwxUAAA==&quot;<br>    }<br>  ],<br>  &quot;latest_replay_id&quot;: &quot;AAAAAAAAwxUAAA==&quot;,<br>  &quot;rpc_id&quot;: &quot;69e1cca4-bb35-465d-95f7-cd8682a2d2e8&quot;,<br>  &quot;pending_num_requested&quot;: 99<br>}</pre><p>That payload field is what we need to decode next. It is not encrypted — it is <strong>Avro-serialized binary data</strong>, then Base64-encoded for safe transport over gRPC. You need the schema (which we already have) to turn it back into readable JSON.</p><p>As soon as PE published you can see the gRPC where we subscribe in 2c) via PostMan display a message and remaining number as 99.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OU51_pmoCwW3xTRg0ezxnA.png" /><figcaption>Check the pending num_request as 99, because you read 1</figcaption></figure><pre>{<br>    &quot;events&quot;: [<br>        {<br>            &quot;event&quot;: {<br>                &quot;headers&quot;: [],<br>                &quot;id&quot;: &quot;01faa11d-954b-4cbc-b275-a4c7c6fc8727&quot;,<br>                &quot;schema_id&quot;: &quot;aolrVzTrnnd-bbgecmvMKw&quot;,<br>                &quot;payload&quot;: &quot;gMrQ6vxlJDAwNWJtMDAwMDBFcE1zckFBRgJCV2VsY29tZSB0byBSYWphdCBCbG9nIG9uIE1lZGl1bSAx&quot;<br>            },<br>            &quot;replay_id&quot;: &quot;AAAAAAAAwxUAAA==&quot;<br>        }<br>    ],<br>    &quot;latest_replay_id&quot;: &quot;AAAAAAAAwxUAAA==&quot;,<br>    &quot;rpc_id&quot;: &quot;69e1cca4-bb35-465d-95f7-cd8682a2d2e8&quot;,<br>    &quot;pending_num_requested&quot;: 99<br>}</pre><h3>Step 7: Decode the Avro payload locally</h3><p>Avro is a compact, schema-driven binary serialization format. Without the schema, the bytes are meaningless; with it, decoding is deterministic.</p><p>Install the Avro library</p><pre>pip3 install avro</pre><p>(Note: the older avro-python3 package is deprecated. Use avro — same import path, actively maintained.)</p><p><strong>Save the schema</strong></p><p>Save the schema_json content from Step 4 as MediumBlog__e.avsc:</p><pre>{<br>  &quot;type&quot;: &quot;record&quot;,<br>  &quot;name&quot;: &quot;MediumBlog__e&quot;,<br>  &quot;namespace&quot;: &quot;com.sforce.eventbus&quot;,<br>  &quot;fields&quot;: [<br>    { &quot;name&quot;: &quot;CreatedDate&quot;, &quot;type&quot;: &quot;long&quot;, &quot;doc&quot;: &quot;CreatedDate:DateTime&quot; },<br>    { &quot;name&quot;: &quot;CreatedById&quot;, &quot;type&quot;: &quot;string&quot;, &quot;doc&quot;: &quot;CreatedBy:EntityId&quot; },<br>    { &quot;name&quot;: &quot;payload__c&quot;, &quot;type&quot;: [&quot;null&quot;, &quot;string&quot;], &quot;doc&quot;: &quot;Data:Text:00Nbm00000Qicqb&quot;, &quot;default&quot;: null }<br>  ]<br>}</pre><p><strong>Decoder script</strong></p><p>Save as decode_avro.py:</p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;Decode a Salesforce Pub/Sub API Base64-encoded Avro payload.<br>Usage:<br>    python3 decode_avro.py &lt;schema_file&gt; &lt;base64_payload&gt;<br>&quot;&quot;&quot;<br>import sys<br>import base64<br>import json<br>import io<br>from datetime import datetime, timezone<br>import avro.schema<br>import avro.io<br><br>def decode_payload(b64_payload: str, schema_path: str) -&gt; dict:<br>    with open(schema_path, &quot;r&quot;) as f:<br>        schema = avro.schema.parse(f.read())<br>    binary = base64.b64decode(b64_payload)<br>    decoder = avro.io.BinaryDecoder(io.BytesIO(binary))<br>    reader = avro.io.DatumReader(schema)<br>    record = reader.read(decoder)<br>    # Convert epoch ms to readable ISO timestamp for any *Date field<br>    for field, value in list(record.items()):<br>        if field.endswith(&quot;Date&quot;) and isinstance(value, int):<br>            record[field] = datetime.fromtimestamp(value / 1000, tz=timezone.utc).isoformat()<br>    return record<br><br>def main():<br>    if len(sys.argv) != 3:<br>        print(__doc__)<br>        sys.exit(1)<br>    record = decode_payload(sys.argv[2], sys.argv[1])<br>    print(json.dumps(record, indent=2))<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>Run it</strong></p><pre>python3 decode_avro.py MediumBlog__e.avsc \<br>  gMrQ6vxlJDAwNWJtMDAwMDBFcE1zckFBRgJCV2VsY29tZSB0byBSYWphdCBCbG9nIG9uIE1lZGl1bSAx</pre><p><strong>Output</strong>:</p><pre>{<br>  &quot;CreatedDate&quot;: &quot;2025-07-07T14:23:11.000+00:00&quot;,<br>  &quot;CreatedById&quot;: &quot;005bm00000EpMsrAAF&quot;,<br>  &quot;payload__c&quot;: &quot;Welcome to Rajat Blog on Medium 1&quot;<br>}</pre><p>A word of caution: never paste production payloads or schemas into public online decoders or AI chat tools. Even with field-level encryption in Salesforce, the schema itself can reveal data structures you would rather not expose. Decode locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9Fy78lMvNFyQxP_af3TDg.png" /></figure><p>Github Directory for python script</p><h4><a href="https://github.com/sharmarajat1984/gRPC_repo/blob/main/README.md">https://github.com/sharmarajat1984/gRPC_repo/blob/main/README.md</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=823063be6cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth in Salesforce via POSTMAN example]]></title>
            <link>https://medium.com/@sharmarajat1984/oauth-in-salesforce-via-postman-example-f78c81f4cb7b?source=rss-12da1fe2c6a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f78c81f4cb7b</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[oauth-flow]]></category>
            <dc:creator><![CDATA[Sharmarajat]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 17:12:31 GMT</pubDate>
            <atom:updated>2024-11-04T17:12:31.324Z</atom:updated>
            <content:encoded><![CDATA[<p>Salesforce supports various OAuth flows, which enable secure API access from external applications. In this post, I’ll walk you through a step-by-step guide to setting up and testing the OAuth 2.0 flow in Salesforce using Postman.</p><p>I always struggle or need to start from scratch when it comes to various salesforce OAuth flows. <br>Here we can go 1 by 1 all the flows with an example.</p><p>Here is a Salesforce URL — <a href="https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_flows.htm&amp;type=5">https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_flows.htm&amp;type=5</a></p><h4>Prerequisites:</h4><ol><li>A Salesforce Developer Org.</li><li>Postman installed on your machine. (And you know how to use it)</li><li>A <strong>Connected App</strong> created in Salesforce with OAuth settings enabled. ( you know how to create the connected app)</li></ol><h3>Different Request and Grant Type</h3><h3>Postman Setup</h3><p>Installed the Postman app or use postman Web application (I assume you know this part, if not please follow postman setup blog)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*q_gvq6qXWyM1d7DQdMkC9g.png" /></figure><p>Search for the Salesforce template as shown above and include in your WorkSpace<br>Add the variable in the postman, this will help you in the different flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*BsmNCtEwIlsHnCLXtLGGLA.png" /></figure><ul><li><strong>URL:</strong> The Salesforce login URL, such as login.salesforce.com.</li><li><strong>Redirect URL:</strong> The URL you provide in the Connected App as the redirect URL. This is used during the Authorization Code flow.</li><li><strong>Secret Token:</strong> The security token associated with your user account, used in the Username-Password flow. Alternatively, you can whitelist the source IPs as trusted IPs to bypass the token requirement.</li><li><strong>Username, Password, Client ID, Client Secret:</strong> These are the standard variables needed for the OAuth flow — I’m sure you’re familiar with them!</li></ul><h3>Token Introspect</h3><p>This service to Introspect your token</p><p>Create this request, so you can introspect the token and know more about the access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKBfmvGAHePjSI0xe_836A.png" /></figure><h3>Token Revoke</h3><p>This service to revokes your access token<br>URL — {{url}}{{site}}/services/oauth2/revoke</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRKyAmm9J65prGRNALn2yg.png" /></figure><p>Create this POST request, so you can revoke the token.</p><h3>1- Client Credentials Flow</h3><ul><li>Ensure you have a Connected App set up. If not, follow the Salesforce steps to create one. — And follow below steps to make it ready for this flow.</li><li>Be sure to check the box for <strong>“Enable Client Credentials Flow”</strong> in the Connected App settings.</li><li>For newer Salesforce orgs, you may need to explicitly enable the client credentials flow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANArqEvbxkjijMVAd-vY3w.png" /></figure><p>. Create a User (API Only profile) and assign it as Run As section of your Connected App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*mirE-aaLOPnIPRLzjuz4xg.png" /><figcaption>Setup →App Manager-&gt; Click on manage on you connected app -&gt; under the Clientr Credentials Flow</figcaption></figure><p>In Post man go to client Credentials flow Request, <strong><em>Make sure you update the Environment Variable as explained earlier.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jcw98roSCw77h-Y5lz3gyg.png" /></figure><p>Bingo you got your access token.</p><p>Before following this pattern for your use case, please review the salesforce recommendation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fit6FfU2ZS0_oO5IvTo9DQ.png" /><figcaption><a href="https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_client_credentials_flow.htm&amp;type=5">https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_client_credentials_flow.htm&amp;type=5</a></figcaption></figure><h3>2- Web Server Flow — PCKEY and Verify</h3><p>This is the tricky one from the POSTman perspective.<br>Prerequisite — Make sure the connected app, has PCKE check box selected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXl9jrJHxedUqS9LZ2gL6Q.png" /><figcaption><strong><em>Enable the Proof key for Code Exchange(PKCE)</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hgc4K4pU5QBnq-8vNnDoPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHLe2RH7bgQ95jmDiy6DuQ.png" /></figure><p>Go to the Authorization tab of the Request and populate the parameters</p><ol><li>Token Name — Name your Token</li><li>Grant Type — Select “<strong><em>Authorization Code</em></strong>”</li><li>Call back URL — Should be same as you use in the connected app</li><li>Auth URL — &lt;&lt;my<a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/authorize">domainURL&gt;&gt;/services/oauth2/authoriz</a>e<br>e.g <a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/authorize">https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/authorize</a></li><li>Access Token URL — <a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/token">&lt;&lt;mydomainURL&gt;&gt;/services/oauth2/toke</a>n<br>e.g <a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/token">https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/token</a></li><li>client id, client secret, Scope(api), State (mystate)</li><li>Client Authentication — select “Send client credentials in a body”</li><li>Under the advance section provide code_challenge and code_verifier <strong><em>(Required for PCKE Verify) <br></em></strong><a href="https://tonyxu-io.github.io/pkce-generator/">https://tonyxu-io.github.io/pkce-generator/</a> <br>to Generate key and verify</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZqFeYMRAKE9X_RDFDRu3Q.png" /></figure><p>9. Click on the Get New Access Token.</p><p>10. This will invoke the salesforce login page and once you authenticate the user. You will see the Access Token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyviqfHSdpe7IdDA3ga9aw.png" /></figure><h3>2 b — Trick to leverage variable from Auth call and use it as environment variable.</h3><p>Once you have the Response from the above, request Click on Use Token Button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*GIhcq36UG0nNr5DJAwgvrQ.png" /></figure><p>In the Pre Request Script of the Request Add the following script to capture the Access token or Refresh token.</p><pre>console.log(&#39;Added by Rajat jsonData&#39;);<br><br>var refresh_token = pm.request.auth.oauth2.get(&#39;refresh_token&#39;);<br>var access_token = pm.request.auth.oauth2.get(&#39;accessToken&#39;);<br><br>const context = pm.environment.name ? pm.environment : pm.collectionVariables;<br>context.set(&quot;accessToken&quot;, access_token);<br>context.set(&quot;_refreshToken&quot;, refresh_token);<br><br>console.log(&#39;Added by Rajat refresh Token&#39; + refresh_token);<br>console.log(&#39;Added by Rajat Access Token&#39; + access_token);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ubzk_S_RpTbC-w0NubHMjg.png" /></figure><p>make the POST/Get request and this will save the Value in the Variable.<br>Check the Console log, you can read the variable.</p><h3>3- User Agent Flow</h3><p>There is a grant type difference b/w <strong><em>Web Server Flow(Authorization Code) and User Agent Flow(implicit)</em></strong>.</p><p>implicit grant Type RFC — <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-4.2">https://datatracker.ietf.org/doc/html/rfc6749#section-4.2</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8csG-i9mucerZapyz8rnQ.png" /><figcaption>grant Type is Implicit</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlMiwUHYCW9ZgD6I1rM0PA.png" /></figure><ol><li>Token Name — Name your Token</li><li>Grant Type — Select “<strong><em>implicit</em></strong>”</li><li>Call back URL — Should be same as you use in the connected app</li><li>Auth URL — &lt;&lt;my<a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/authorize">domainURL&gt;&gt;/services/oauth2/authoriz</a>e<br>e.g <a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/authorize">https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/authorize</a></li><li>Access Token URL — <a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/token">&lt;&lt;mydomainURL&gt;&gt;/services/oauth2/toke</a>n<br>e.g <a href="https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/token">https://resilient-badger-9de0sr-dev-ed.trailblaze.my.salesforce.com/services/oauth2/token</a></li><li>client id, Scope(api), State (mystate)</li><li>Client Authentication — select “Send client credentials in a body”</li><li>Under the advance section provide code_challenge and code_verifier <strong><em>(Required for PCKE Verify) <br></em></strong><a href="https://tonyxu-io.github.io/pkce-generator/">https://tonyxu-io.github.io/pkce-generator/</a> <br>to Generate key and verify</li></ol><h3>4- Refresh Flow</h3><p>We use the refresh token to request a new access token, especially in scenarios where a client (like a mobile app) authorizes once and then uses the refresh token to get new access tokens when they expire.</p><p>Ensure that <strong>refresh_token</strong> is included in the scope of the Connected App.</p><p>Additionally, there’s an option to enable refresh token rotation in the Connected App settings.</p><p>Note: Implicit grant(app-client) will not provide the refresh token, so we are going to leverage Web server flow for the demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*601EdzjxyRkxaOd144Ne_A.png" /></figure><p>Make sure under connected App policy, you don’t have the correct setting. Otherwise you may receive as “Token Validity Expired”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyTA0dC5XZ-wYw0p2KAxcA.png" /></figure><p>In #2 add the Scope in the Scope setting of the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_TuhIRaxVmmFIq_Afhnbg.png" /></figure><p>In your response you can see the Refresh Token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*mEgO7cLEq4UL7ANCbKs1qg.png" /></figure><p><strong>Note</strong>: Refer to step 2b for guidance on setting values in environment variables, which eliminates the need for manually copying and pasting variables.</p><p>Now, moving back to the Post Refresh call:</p><ul><li>First, make a call to <strong>Revoke Token</strong> (as explained earlier).</li><li>Then, use <strong>Introspect Token</strong> to confirm if the token has been successfully revoked.</li><li>After that, open the <strong>POST Refresh Token</strong> call in your collection, execute it, and you should receive a new access token.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ulYslC2KFSlnSbKdtCw4w.png" /></figure><h3>5 — JWT OAuth Flow</h3><p>This is my preferred flow, and I highly recommend it for M2M (Machine-to-Machine) integrations.</p><p><strong><em>Create a certificate and private key</em></strong></p><p>(You can search online or, if you’re on a Mac, follow the specific steps.)<br>Each company or enterprise typically has dedicated teams or groups responsible for generating certificates and keys. However, for the purpose of this POC, I’ll provide a general overview.</p><p>Also, based on your user case select Admin pre approve user or not</p><pre>Snippet from the salesforce documentation<br>Assuming that the JWT is valid and that the connected app has prior approval, <br>Salesforce issues an access token. Prior approval happens in one of these ways:<br>  If your connected app policy is set to Admin approved users are pre-authorized,<br>  you can use profiles and permission sets.<br><br>  If your connected app policy is set to All users may self-authorize, <br>  you can use end-user approval and issuance of a refresh token. <br>  However, the client isn’t required to have a current or stored refresh token. <br>  The client also isn’t required to pass a client secret to the token endpoint.</pre><p><strong><em>Open Terminal and type following commands</em></strong></p><pre>openssl genpkey -des3 -algorithm RSA -pass pass:Testing@1234 -out server-pass.key -pkeyopt rsa_keygen_bits:2048<br><br>openssl rsa -passin pass:Testing@1234 -in server.pass.key -out server.key<br><br>openssl req -new -key server.key -out server.csr<br>(Enter the values)<br><br>openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.cr</pre><p>n your Connected App, upload the certificate by navigating to <strong>OAuth Enable Settings</strong> → <strong>Select Digital Certificate</strong> and upload the file.</p><p>The next step is to generate the JWT request. The following websites will be useful:</p><ul><li><a href="https://jwt.io/">JWT Token Generator</a></li><li><a href="https://www.unixtimestamp.com/">Unix Timestamp Converter</a></li></ul><p>Now, let’s take a look at the payload that needs to be signed with the certificate and key.</p><pre>Header Value<br>{&quot;alg&quot;:&quot;RS256&quot;}<br><br>Payload Value<br>{<br>&quot;iss&quot; : &quot;3MVG9XgkMlifdwVBZtBNdHIISaisbdgvPZdbkMO42KC4q29Fh3EuInl7858SQFLfa8y42pSVEYqyz.XfPaOOs&quot;,<br>&quot;sub&quot;: &quot;sharmarajat1984@wise-hawk-ga9rko.com&quot;,<br>&quot;aud&quot;: &quot;https://login.salesforce.com&quot;,<br>&quot;exp&quot;: &quot;1727406958&quot;<br>}<br><br>Verify signature<br>Certificate you created earlier</pre><p>iss -&gt; is the Client ID from the connected App<br>sub -&gt; is the Username in salesforce<br>aud -&gt; URL where login happens<br>exp → expire time for the token (use the unix timestamp converter)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeCqsNcuL2Mda-9og1SQhA.png" /></figure><p>In the screenshot above, for the certificate and pass key, open the file in Notepad and copy the text.</p><p><strong>Tip</strong>: From personal experience, be cautious — the payload is case-sensitive, so double-check everything!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK-eKwujedDZGO2UdhmmZQ.png" /></figure><p>Copy the generated JWT token from the <a href="https://jwt.io/">jwt.io</a> website and paste it into the <strong>assertion</strong> attribute before submitting the request for an access token.</p><p><strong>Tip</strong>: JWT (pronounced “JOT”) tokens consist of three parts, separated by dots, representing the header, payload, and signature.</p><h3>6- OpenID Connect Dynamic Client Registration for External API Gateways</h3><p>Not Covering here, Please refer salesforce document for the same.</p><h3>7- OAuth 2.0 Device Flow for IoT Integration</h3><h3>OAuth 2.0 Authorization and Session Management for Hybrid Apps</h3><p>We’re not covering this here, but in simple terms, this is the web (UI-based) flow, which is equivalent to the user-agent, web-server, and refresh-token flows discussed earlier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f78c81f4cb7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>