When To Go Asynchronous

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 13

When to Go Asynchronous

Processing a very large number of records


Making callouts to external web services.
Creating a better and faster user experience

Here are some limitations to consider before using a future method.


•You can’t track execution because no Apex job ID is returned.
•Parameters must be primitive data types, arrays of primitive data types, or collections of
primitive data types. Future methods can’t take objects as arguments.
•You can’t chain future methods and have one call another.
Apex is a programming language that uses Java-like syntax and acts like database stored
procedures. Apex enables developers to add business logic to system events, such as button clicks,
updates of related records, and Visualforce pages.

As a language, Apex is:

•Hosted—Apex is saved, compiled, and executed on the server—the Lightning Platform.

•Object oriented—Apex supports classes, interfaces, and inheritance.

•Strongly typed—Apex validates references to objects at compile time.

•Multitenant aware—Because Apex runs in a multitenant platform, it guards closely against


runaway code by enforcing limits, which prevent code from monopolizing shared resources.

•Integrated with the database—It is straightforward to access and manipulate records. Apex
provides direct access to records and their fields, and provides statements and query languages to
manipulate those records.

•Data focused—Apex provides transactional access to the database, allowing you to roll back
operations.

•Easy to use—Apex is based on familiar Java idioms.

•Easy to test—Apex provides built-in support for unit test creation, execution, and code coverage.
Salesforce ensures that all custom Apex code works as expected by executing all unit tests prior to
any platform upgrades.
•Versioned—Custom Apex code can be saved against different versions of the API.

Like other object-oriented programming languages, these are some of the language constructs that
Apex supports:

•Classes, interfaces, properties, and collections (including arrays).

•Object and array notation.

•Expressions, variables, and constants.

•Conditional statements (if-then-else) and control flow statements (for loops and while loops).

Unlike other object-oriented programming languages, Apex supports:

•Cloud development as Apex is stored, compiled, and executed in the cloud.

•Triggers, which are similar to triggers in database systems.

•Database statements that allow you to make direct database calls and query languages to query and
search data.

•Transactions and rollbacks.

•The global access modifier, which is more permissive than the public modifier and allows access
across namespaces and applications.

•Versioning of custom code.

In addition, Apex is a case-insensitive language.

The SOQL query uses an inner query—(SELECT Id FROM Opportunities)—to get related opportunities of
accounts.

•The SOQL query is connected to the trigger context records by using the IN clause and binding
the Trigger.New variable in the WHERE clause—WHERE Id IN :Trigger.New. This WHERE condition
filters the accounts to only those records that fired this trigger.
To create more efficient text searches
Limit which data you’re searching through

•Limit which data you’re returning

To limit which data is searched, use IN SearchGroup. You can search for name, email, phone, sidebar,
or all fields. For example, if you want to search only for an email, you search through only email
fields.
FIND {jsmith@cloudkicks.com} IN EMAIL FIELDS RETURNING Contact

The first thing to know is that although they’re both called query languages, SOQL is used only to
perform queries with the SELECT statement. SOQL has no equivalent INSERT, UPDATE, and
DELETE statements. In the Salesforce world, data manipulation is handled using a set of methods
known as DML (Data Manipulation Language). We’ll talk more about DML shortly. For now, you
just need to know how to query Salesforce data using the SELECT statement that SOQL provides.
One big difference you’ll notice right away is that SOQL has no such thing as SELECT *. Because
SOQL returns Salesforce data, and that data lives in a multi-tenanted environment where everyone
is kind of "sharing the database,” a wildcard character like * is asking for trouble. Honestly
speaking, it’s just too easy to fire up a new SQL query and type in SELECT * FROM SOME-TABLE,
especially when you don’t know what the table field names are. This action could severely impact
other tenants in your shared environments. Would you mow your lawn Sunday morning at 7?
That’s just rude and disrespectful.
In SOQL, you specify each field name to return. Beyond that, the SELECT statement that SOQL
provides is similar to SQL. You’ll find writing SOQL queries pretty easy. But here’s what you need
to know: Although SQL and SOQL are similar, they’re not the same. SOQL doesn’t support some of
the more advanced features that the SQL SELECT statement does. But on the Salesforce platform,
you really don’t need all those extra features. SOQL offers just what you need in a way that makes
you feel right at home.
What About Aggregates?
Yep, SOQL has aggregates, and they work pretty much the way you expect them to. Well, kind of.
The big thing to be aware of when working with aggregates is that for most functions your result is
returned as an AggregateResult type.

SOQL or SOSL?
Which one do you use? I’m sure you won’t be surprised to hear this: It depends on what you’re
trying to accomplish.
If you need data from a single object and you specifically know the criteria for that object, you’ll
most likely want to use SOQL. In fact, most of your queries will probably be in SOQL.
SOSL is most useful when you don’t know the exact fields and objects that your data resides in, and
you need to search across multiple objects. This is especially true when those objects aren’t related
because SOQL works only with related objects.
SOSL
FIND {joey} IN ALL FIELDS RETURNING Account(Name), Contact(LastName, FirstName),
ContentVersion(Title)

Selective Queries

For all standard and custom tables, certain fields are automatically flagged to be indexed. These
fields include the following:

The paradigm of event-based communication revolves around a publisher-subscriber model—a


sender broadcasts a message that one or more receivers capture. It’s like radio transmission—a
transmitter tower broadcasts a radio signal, and receivers get the signal if they’re tuned to the right
frequency.
Components of Event-Driven Systems
Event
A change in state that is meaningful in a business process. For example, placement of a purchase
order is a meaningful event, because the order fulfillment center expects to receive a notification
before processing an order.

Event message
A message that contains data about the event. Also known as an event notification. For example, an
event message can be a notification about an order placement containing information about the
order.

Event producer
The publisher of an event message. For example, an order placement app.

Event channel
A stream of events on which an event producer sends event messages and event consumers read
those messages. For platform events, the channel is for one platform event and groups all event
messages for that platform event.

Event consumer
A subscriber to a channel that receives messages from the channel. For example, an order
fulfillment app that is notified of new orders.

Event bus
A communication and storage service that enables event streaming using the publish-subscribe
model. The event bus enables the retrieval of stored event messages at any time during the retention
window.

All field types that platform events support are:


•Checkbox
•Date
•Date/Time
•Number
•Text
•Text Area (Long)

Asynchronous Apex
In a nutshell, asynchronous Apex is used to run processes in a separate thread, at a later time.
An asynchronous process is a process or function that executes a task "in the background" without
the user having to wait for the task to finish.
User efficiency
Let's say you have a process that makes many calculations on a custom object whenever an
Opportunity is created. The time needed to execute these calculations could range from a minor
annoyance to a productivity blocker for the user. Since these calculations don't affect what the user
is currently doing, making them wait for a long running process is not an efficient use of their time.
With asynchronous processing the user can get on with their work, the processing can be done in
the background and the user can see the results at their convenience.
Scalability
By allowing some features of the platform to execute when resources become available at some
point in the future, resources can be managed and scaled quickly. This allows the platform to handle
more jobs using parallel processing.
Higher Limits
Asynchronous processes are started in a new thread, with higher governor and execution limits. And
to be honest, doesn’t everyone want higher governor and execution limits?

One of the main benefits of running asynchronous Apex is higher governor and execution limits.
For example, the number of SOQL queries is doubled from 100 to 200 queries when using
asynchronous calls. The total heap size and maximum CPU time are similarly larger for
asynchronous calls.
Not only do you get higher limits with async, but also those governor limits are independent of the
limits in the synchronous request that queued the async request initially. That’s a mouthful, but
essentially, you have two separate Apex invocations, and more than double the processing
capability. This comes in handy for instances when you want to do as much processing as you can
in the current transaction but when you start to get close to governor limits, continue
asynchronously.

How Asynchronous Processing Works


Asynchronous processing, in a multi-tenant environment, presents some challenges:
Ensure fairness of processing
Make sure every customer gets a fair share of processing resources.
Ensure fault tolerance
Make sure no asynchronous requests are lost due to equipment or software failures.
The platform uses a queue-based asynchronous processing framework. This framework is used to
manage asynchronous requests for multiple organizations within each instance. The request
lifecycle is made up of three parts:
Enqueue
The request gets put into the queue. This could be an Apex batch request, future Apex request or
one of many others. The platform will enqueue requests along with the appropriate data to process
that request.
Persistence
The enqueued request is persisted. Requests are stored in persistent storage for failure recovery and
to provide transactional capabilities.
Dequeue
The enqueued request is removed from the queue and processed. Transaction management occurs in
this step to assure messages are not lost if there is a processing failure.

Each request is processed by a handler. The handler is the code that performs functions for a
specific request type. Handlers are executed by a finite number worker threads on each of the
application servers that make up an instance. The threads request work from the queuing framework
and when received, start a specific handler to do the work.
Best Practices
Since every future method invocation adds one request to the asynchronous queue, avoid design
patterns that add large numbers of future requests over a short period of time. If your design has the
potential to add 2000 or more requests at a time, requests could get delayed due to flow control.
Here are some best practices you want to keep in mind:
• Ensure that future methods execute as fast as possible.
• If using Web service callouts, try to bundle all callouts together from the same future method, rather
than using a separate future method for each callout.
• Conduct thorough testing at scale. Test that a trigger enqueuing the @future calls is able to handle a
trigger collection of 200 records. This helps determine if delays may occur given the design at
current and future volumes.
• Consider using Batch Apex instead of future methods to process large number of records
asynchronously. This is more efficient than creating a future request for each record.
Things to Remember
Future methods are a great tool, but with great power comes great responsibility. Here are some
things to keep in mind when using them:
• Methods with the future annotation must be static methods, and can only return a void type.
• The specified parameters must be primitive data types, arrays of primitive data types, or collections
of primitive data types; future methods can’t take objects as arguments.
• Future methods won’t necessarily execute in the same order they are called. In addition, it’s
possible that two future methods could run concurrently, which could result in record locking if the
two methods were updating the same record.
• Future methods can’t be used in Visualforce controllers in getMethodName(), setMethodName(),
nor in the constructor.
• You can’t call a future method from a future method. Nor can you invoke a trigger that calls a future
method while running a future method. See the link in the Resources for preventing recursive future
method calls.
• The getContent() and getContentAsPDF() methods can’t be used in methods with the future
annotation.
• You’re limited to 50 future calls per Apex invocation, and there’s an additional limit on the number
of calls in a 24-hour period. For more information on limits, see the link below.

Only use Batch Apex if you have more than one batch of records. If you don't have enough records
to run more than one batch, you are probably better off using Queueable Apex.
•Tune any SOQL query to gather the records to execute as quickly as possible.
•Minimize the number of asynchronous requests created to minimize the chance of delays.
•Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to
guarantee that the trigger won’t add more batch jobs than the limit.

Queueable Apex allows you to submit jobs for asynchronous processing similar to future methods
with the following additional benefits:
•Non-primitive types: Your Queueable class can contain member variables of non-primitive data
types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
•Monitoring: When you submit your job by invoking the System.enqueueJob method, the method
returns the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its
progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by
querying your record from AsyncApexJob.
•Chaining jobs: You can chain one job to another job by starting a second job from a running job.
Chaining jobs is useful if you need to do some sequential processing.

Things to Remember
Queueable Apex is a great new tool but there are a few things to watch out for:
• The execution of a queued job counts once against the shared limit for asynchronous Apex method
executions.
• You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
• When chaining jobs, you can add only one job from an executing job with System.enqueueJob,
which means that only one child job can exist for each parent queueable job. Starting multiple child
jobs from the same queueable job is a no-no.
• No limit is enforced on the depth of chained jobs, which means that you can chain one job to
another job and repeat this process with each new child job to link it to a new child job. However,
for Developer Edition and Trial orgs, the maximum stack depth for chained jobs is 5, which means
that you can chain jobs four times and the maximum number of jobs in the chain is 5, including the
initial parent queueable job.

https://help.salesforce.com/s/articleView?id=sf.code_apex_flex_queue.htm&type=5

Monitoring Future Jobs


Future jobs show up on the Apex Jobs page like any other jobs. However, future jobs are not part of
the flex queue currently.
You can query AsyncApexJob to find your future job, but there’s a caveat. Since kicking off a future
job does not return an ID, you have to filter on some other field such as MethodName, or JobType,
to find your job. There are a few sample SOQL queries in this Stack Exchange post  that might help.
Monitoring Queued Jobs with SOQL
To query information about your submitted job, perform a SOQL query on AsyncApexJob by
filtering on the job ID that the System.enqueueJob method returns.
AsyncApexJob jobInfo = [SELECT Status, NumberOfErrors
FROM AsyncApexJob WHERE Id = :jobID];

Copy

Monitoring Queue Jobs with the Flex Queue


The Apex Flex queue enables you to submit up to 100 batch jobs for execution. Any jobs that are
submitted for execution are in holding status and are placed in the Apex Flex queue. Up to 100
batch jobs can be in the holding status.
Jobs are processed first-in first-out—in the order in which they’re submitted. You can look at the
current queue order and shuffle the queue, so that you could move an important job to the front, or
less important ones to the back.
When system resources become available, the system picks up the next job from the top of the Apex
Flex queue and moves it to the batch job queue. The system can process up to five queued or active
jobs simultaneously for each organization. The status of these moved jobs changes from Holding to
Queued. Queued jobs get executed when the system is ready to process new jobs. Like other jobs,
you can monitor queued jobs in the Apex Jobs page.
Monitoring Scheduled Jobs
After an Apex job has been scheduled, you can obtain more information about it by running a
SOQL query on CronTrigger. The following sample queries the number of times the job has run,
and the date and time when the job is scheduled to run again. It uses a jobID variable which is
returned from the System.schedule method.
CronTrigger ct = [SELECT TimesTriggered, NextFireTime FROM CronTrigger
WHERE Id = :jobID];

Copy
If you’re performing this query inside the execute method of your schedulable class, you can obtain
the ID of the current job by calling getTriggerId on the SchedulableContext argument variable.
global class DoAwesomeStuff implements Schedulable {
global void execute(SchedulableContext sc) {
// some awesome code
CronTrigger ct = [SELECT TimesTriggered, NextFireTime FROM
CronTrigger WHERE Id = :sc.getTriggerId()];
}
}

Copy
You can also get the job’s name and the job’s type from the CronJobDetail record associated with
the CronTrigger record. To do so, use the CronJobDetail relationship when performing a query on
CronTrigger. This example retrieves the most recent CronTrigger record with the job name and type
from CronJobDetail.
CronTrigger job = [SELECT Id, CronJobDetail.Id, CronJobDetail.Name,
CronJobDetail.JobType FROM CronTrigger ORDER BY CreatedDate DESC LIMIT
1];

Copy
Alternatively, you can query CronJobDetail directly to get the job’s name and type. The following
example gets the job’s name and type for the CronTrigger record queried in the previous example.
The corresponding CronJobDetail record ID is obtained by the CronJobDetail.Id expression on the
CronTrigger record.
CronJobDetail ctd = [SELECT Id, Name, JobType FROM CronJobDetail WHERE
Id = :job.CronJobDetail.Id];
Copy
And lastly, to obtain the total count of all Apex scheduled jobs, excluding all other scheduled job
types, perform the following query. Note the value '7' is specified for the job type, which
corresponds to the scheduled Apex job type. See CronJobDetail in the Resources section for a list of
all types.
SELECT COUNT() FROM CronTrigger WHERE CronJobDetail.JobType = '7’

Two models of developing web app


Page Centric web application model

• great to serve basic functionality.


• not offer great user interactive experience
• server side generate user interaction

App Centric mode


• great user experience
• client side

Three options that offered by Salesforce

Classic Visualforce
• UI Generation - Server-side
• Data and Business Logic-Apex standard or custom controller
• Workflow
1. User requests a page
2. The server executes the page’s underlying code and sends the resulting HTML to the
browser
3. The browser displays the HTML
4. When the user interacts with the page, return to step one.
• Pros
1. Tried and true model
2. Easy to implement for greater productivity
3. Naturally splits large applications into small, manageable page
4. Has built-in metadata integration
• Caveats
1. Limited interactivity (aside from added JavaScript functionality)
2. Higher latency, which degrades mobile performance

Visualforce as a JavaScript Application Container


-Empty visualforce with javascript code.In other word, Visualforce just add as javascript
container.
• UI Generation -Client-side (mostly JavaScript)
• Data and Business Logic- Remote Objects or JavaScript Remoting
• Workflow
1. The user requests the “empty” Visualforce page containing only JavaScript includes
2. The page is returned to the browser
3. The browser loads the JavaScript application
4. The JavaScript application generates the UI
5. When a user interacts with the application, the JavaScript modifies the user interface as
needed (return to the previous step).
• Pros
1. Enables highly interactive and immersive user experiences
• Caveats
1. Complex
2. No built-in metadata integration
3. Lack of an integrated developer experience. The Force.com Developer Console doesn’t
explicitly support these JavaScript applications. Need to store javascript library in Static
Resource

Lightning Components
• UI Generation-Client-side (JavaScript)
• Data and Business Logic-Apex controller
• Workflow
1. The user requests an application or a component
2. The application or component bundle is returned to the client
3. The browser loads the bundle
4. The JavaScript application generates the UI
5. When the user interacts with the page, the JavaScript application modifies the user
interface as needed (return to previous step)
• Pros
1. Enables highly interactive and immersive user experiences
2. Aligns with Salesforce user interface strategy
3. Built on metadata from the foundation, accelerating development
4. The Developer Console supports Lightning components, so there’s an integrated
developer experience
• Caveats
1. Higher learning curve compared to Visualforce
2. Higher complexity than Visualforce—you’re building an application, not a page
3. Since Lightning components are new, there are still some features that aren’t supported
4. There are a limited number of out-of-the-box components

https://www.salesforceben.com/salesforce-summary-visualforce-in-lightning-experience/

You might also like