0% found this document useful (0 votes)
2 views34 pages

Module 4 Application Design

Module 4 covers application design and coding best practices, focusing on caching mechanisms in Demandware®, including dynamic page caching and Akamai caching. It emphasizes the importance of efficient caching for performance, detailing various caching levels, session handling, and best practices for API and object caching. The module also addresses session persistence, customer states, and basket persistence options within the Demandware® platform.

Uploaded by

Dx Cat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Module 4 Application Design

Module 4 covers application design and coding best practices, focusing on caching mechanisms in Demandware®, including dynamic page caching and Akamai caching. It emphasizes the importance of efficient caching for performance, detailing various caching levels, session handling, and best practices for API and object caching. The module also addresses session persistence, customer states, and basket persistence options within the Demandware® platform.

Uploaded by

Dx Cat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 4

Application Design &


Coding Best Practices
Lesson 1: Application Design - Caching
Objectives:

 Leverage dynamic page caching, understand Akamai caching.


 Understand the different levels of caching in Demandware®.
 Explain API and Object caching.
 Identify best practices that impact caching.
 Understand session handling, request serialization and pipeline
events.

Demandware® utilizes several forms of caching mechanisms to increase


site performance. The Demandware® platform manages caching
internally by the system, although some aspects of caching are controlled
by the code / developer. Review a summary of what you learned already
before getting into more details.

Web Server and Akamai Caching

Demandware® offers caching for dynamic and static data


at several levels and it is extremely important to leverage
these mechanisms as efficiently as possible in order to
create a solution that scales smoothly.

Pipeline Caching

The primary caching mechanism for dynamic data is the


page cache on the web server. This cache is managed by the
Demandware® Web Adapter. This cache is used to store any type of
presentation asset to avoid the execution of application logic for every
request for the same data result. Leveraging this mechanism improves
response times greatly under load.

©2012 Demandware, Inc. Version 11/6/2013 Page 1


Module 4: Application Design

Figure 1: Demandware web server caching mechanism

When a request for a page gets into the web server, the web adapter
checks to see whether a cached response for this request is stored in the
page cache. If one can be found, the web adapter passes this content to
the web server to return on the request. No request is made to the
application layer and no pipelines or custom logic is executed.

If one cannot be found, the request is routed to the application layer for
processing. When the application layer returns a response to the web
adapter, if the page is flagged as cacheable, a copy of the response is
stored in the page cache. Template results are flagged as cacheable using
the <iscache /> ISML tag.

Note: Personalized information being re-usable for different


customers can be cached as well. The template then needs to be marked
as cacheable and the vary_by attribute set according. Check
documentation. To allow personalization, OnSession and OnRequest
pipelines exist to provide personalization information to the web adapter.
These pipeline handlers are called before the web adapter tries to retrieve
a cached page. Please look for more detailed explanation lesson 2.

Response assets are stored in the page cache under fully qualified URLs.

This means that all four of the following URLs, although they may produce
the exact same result, are stored separately, or as four different
responses in the page cache:

[Link]/Partners/partners,default,[Link]

[Link]/Partners/partners,default,[Link]

[Link]

[Link]/Partners/partners,default,[Link]

The same applies to parameters, meaning the following URLs, while


producing the exact same result, are also stored as two separate copies in
the page cache:

©Demandware, Inc. Version Date 11/6/2013 Page 2


Module 4: Application Design
[Link]/Partners/partners,default,[Link]

[Link]/Partners/partners,default,[Link]?src=xyz

For this reason it is meaningful to only pass relevant parameters in


cached requests, in particular when the goal is to re-use the asset across
multiple pages via includes, for example in product tiles. Unique
parameters reduce the cache hit rate overall, and also unnecessarily bloat
the cache size, adding a minor amount of latency to the lookup of cached
assets.

Remote Includes, Pipeline Includes

All remote pipeline includes implemented in ISML templates are basically


handled the same way. In a first step, the application server provides in
the returned document for the main request a certain number of markers
named “wainclude” reflecting the pipelines to be called to fill the
individual places in the template. The document is stored in the page
cache (if marked cacheable) and then parsed to resolve all these
placeholders. So every remote include causes another pipeline
transparently being called from the web server to resolve these includes.
This is done sequentially until all placeholders are resolved. Finally, the so
created response document is returned to the requesting browser.

Static Caching

Demandware® also uses Akamai for caching static content. Akamai has
thousands of servers around the globe that cache static content.
Demandware® provides a utilities class ([Link]) for, among
other things, generating urls to static content on the integrated Akamai
servers. Requests to this content are routed to the nearest Akamai
server, if a file is not available on that server, Akamai routes to the closest
available server and cache the returned file on the server that received
the request. Demandware® integrates Akamai technology on production
and development instances.

Figure 1 Demandware static caching mechanism

©Demandware, Inc. Version Date 11/6/2013 Page 3


Module 4: Application Design
Akamai is integrated into development instances so that clients have an
instance that is nearly identical to production behavior for testing
purposes.

Below is an example of a typical Akamai enabled URL to static content:

[Link]
tes-Demandware®-Site/Sites-Demandware®-
Library/default/v1323978275508/images/[Link]

Note: the XXXXXXXXXX in the URL. Each replication of static content


generates a new version number in the URL. This guarantees that
changed static content will always be displayed regardless of any previous
“expires”, “max-age” or “TTL” settings. Demandware® sets the TTL value
at Akamai to 86,400 seconds by default. This value can be set in Business
Manager under Administration > Sites > Manage Sites > Site > Cache Tab.

On production you need to request that support change this value for
you.

Currently, Demandware® does not allow indexing of Akamai content as


this is a binary setting for Demandware® meaning Demandware® would
need to enable it for all or no customers. Demandware® is currently
working on a design to make this more flexible for individual clients.

Note: Be aware of not existing images/script/css, as the requests for


these missing resources are going all time all way down through Akamai,
Demandware and to the file system, looking up a file and returning then a
404 error code.

Advanced Caching Practices

For each request that ends in a template, the


inclusion of the iscache tag within the template
determines if that page is cached or not cached
(generated for each request).

Page cache expiration / duration is managed by


setting daily (GMT) or relative (up to 24 hours) caching modes and
durations within the iscache tag.

Session

Page caching can be personalized on a promotion and price book level


using varyBy = “price_promotion” attribute of the iscache tag. This varyby

©Demandware, Inc. Version Date 11/6/2013 Page 4


Module 4: Application Design
attribute should only be set on cached pages that actually vary output
based on personalization, for example, expecting unique outputs per
customer group.

Note: These so called personalization groups are recalculated every


time session attributes are updated. They are depending on price books,
promotions and “AB” tests only. But you can use it to create different
behavior for distinct customer groups creating promotions accordingly!

Form Requests

Use HTTP GET for all form submissions that require a cached response.
Using the form method POST and other form methods bypass the
Demandware® page cache.

Redirect Templates are cached, especially for heavily loaded pages like
RedirectURL-Start.

The following are best practices for considering caching in code design:

Best Practices:

When you think about caching, keep in mind


 Session has to be used with care.
 Form Requests – only with GET
 Locally included templates, remote includes
(iscomponent vs. remote includes)
 URL Diversity (is discussed in Site Optimization in more
detail later)
 Redirect templates

API Caching

Use caching capabilities of REST type web


services. API supports caching of responses
depending on time, usage and size. Use
HTTPClient capabilities and set caching to e.g.
30 minutes.

Use [Link](), be careful


regarding session information and personalized content.

The Demandware® Open Commerce API provides caching capabilities as


well. All resources providing cacheable information like product, category,

©Demandware, Inc. Version Date 11/6/2013 Page 5


Module 4: Application Design
product search and promotion can be configured to be cached for a given
time. This shall be used to optimize performance.

Object Caching

Internally, the system uses an object cache


(object relation mapper ORM) to avoid
duplicate accesses to the database, e.g. to
fetch product information. This cache is
transparent to the custom application, but
improves performance significantly. Items
which are fetched initially can be looked up easily using their primary key.

ORM churn is frequently rotating objects in memory. This happens for


instance while running jobs looking up many database objects one by one
without reusing them again. This explains why post-processing of data in
the application server does not work well and should not be
implemented. Use lookup by ID wherever possible to actually leverage
this caching capability and avoid complex object queries – as these hit the
database.

Objects are built during a request like ProductVariationModel,


ProductPriceModel, ProductAvailabilityModel are currently not cached
during a request, so reusing them is helpful.

©Demandware, Inc. Version Date 11/6/2013 Page 6


Module 4: Application Design
Lesson 2 Session and Request Handling, Object Storage
Objectives:

 Explain session persistence in Demandware®.


 Understand customer states.
 Explain the basket persistence options in Demandware®.
 Explain the how session requests are triggered using pipelines and
APIs.
 Understand pipeline events and customization as well as session and
request object customization.
 Understand how custom attributes and localizable data are stored.

The Demandware® platform, being a web


based platform, uses a request/response
model to interact will clients. By nature the
request/response model of the web is stateless
due to the use of the HTTP protocol, which
each request and response to the server is in
essence independent of each other.

In an ecommerce environment, it is important to establish and maintain


state between each request made by a client to enable the most basic to
complex ecommerce requirements. For example, the recognition and
authentication of a storefront customer and basket throughout the
shopping experience.

The Demandware® platform maintains state of the shopping experience


for a user by utilizing a combination of client side and server side
techniques handled internally by the Demandware® system. This allows
the stateless requests and responses to be associated together into a
session. No code customizations are necessary or should be made to
interrupt the internal session handling.

Session State and Session Persistence

A session is created on the Demandware® platform on the first request to


the server. On this first request cookies are set on the user’s browser.
One cookie, “dwsid” contains the generated session ID, which is a unique
identifier of the newly created session which is sent back to the
Demandware® for each subsequent request. This cookie and session ID is
what ties the subsequent requests together into a session.

The duration of the session is determined by two types of session


timeouts listed below. Session timeout times durations are based on PCI

©Demandware, Inc. Version Date 11/6/2013 Page 7


Module 4: Application Design
compliance guidelines. They are hardcoded in the platform and cannot be
changed.

A soft session timeout occurs 30 minutes after the last request has been
made to the server. The soft timeout performs automatic logout, and
clearing of all privacy data stored in the session

A hard timeout renders a session invalid after 6 hours, independent of


whatever the session is still in use. The hard timeout makes it impossible
to re-open a session. This hard timeout prevents that a session id, which
for example is accidentally copied into a URL, can be actually used to start
a session.

After a session timeout, on the next request to the storefront a new


session is created and a new “dwsid” cookie is set on the client with the
new session id. Also, in the case the brower is closed before the session
timeout period or cookies are cleared on the browser a new session and
“dwsid” cookie will be set on the next request to the storefront.

These cookies are managed by Demandware:


 dwsid – contains the session ID
 dwanonymous – stores the anonymous user id to retrieve the basket
if a customer comes back later
 dwcustomer – the id of a customer registered once and requested
“to be remembered”
 dwpersonalization – participation in an AB test lasting longer than a
session
 dwsourcecode – the applied source code
 dwsecure – request id to avoid any highjacking of a secure session

Demandware® uses session stickiness and always routes requests within a


single session to the same application server but not necessarily to the
same web server – so a request could be cached in one web server and
refreshing the page might cause a newer / older version showing up.

Session data is also serialized and stored in a persistent location. In case


of a fail-over situation, requests are re-routed to another application
server, which than loads the session data from the persistent storage.

Customer State

After the session is created, the storefront user can be identified as one
of the following:

Anonymous:

©Demandware, Inc. Version Date 11/6/2013 Page 8


Module 4: Application Design
An anonymous user is a user that has a session ID but has not logged into
the site and is not recognized.

Recognized:

In Site Genesis, when a user logs into their customer account, they have
the option to select a check box labeled “Remember Me”. If this is
checked, after successful login to the customer account a cookie is set on
the browser which is used to identify the customer as recognized when
the next session is initiated. A recognized user is not authenticated; the
customer still is required to login in order to view customer specific
information (for example, My Account)

Authenticated:

An authenticated user that has logged into the site as a Demandware®


customer on the storefront.

Basket Persistence

Based on configurable options mentioned below, another unique


identifier is generated on the first request to handle basket persistence
between storefront sessions. This unique identifier is saved as a cookie
associated with the basket for the user. For anonymous users the cookie
is prefixed by “anonymous_” followed by a generated key. This value of
this cookie is the UUID (internal unique identifier) of the basket in the
Demandware® system.

The lifetime of the cookie set by the Demandware® platform when an


anonymous customer enters the site for the first time adheres to certain
international data storage regulations. Due to this, the maximum lifetime
of any cookie set by the Demandware® platform is 6 months.

There are several basket persistence options that can be set in the
Business Manager within Preferences. Below is the description of how
basket persistence is defined for registered and non-
registered/anonymous storefront customers:

Basket Persistence allows choosing whether the basket of a customer


should disappear when the session expires or should be preserved.

The following rules apply:

General Rules

If a customer registers or logs in, the basket of the current anonymous or


registered customer remains in the session and becomes the basket of
the new customer (change of ownership).

©Demandware, Inc. Version Date 11/6/2013 Page 9


Module 4: Application Design
The basket of a registered customer disappears from the session when
the customer logs out.

Baskets Not Persistent

All baskets disappear at the end of the storefront session. The basket of
the customer's previous session is not restored if the customer returns
the storefront in a new session.

Baskets Persistent for Authenticated Customers O nly

Baskets of registered customers are stored for the duration configured


with the preference 'Basket Lifetime'. The basket of a registered
customer's previous session is restored if the customer returns the
storefront and logs in. If a customer logs in, and there is no current
session basket, the basket of the registered customer's previous session is
restored. Otherwise the current session basket becomes the basket of the
customer and the previous basket is provided through the API.

Baskets Persistent for Registered Customers O nly

Baskets of registered customers are stored for the duration configured


with the preference 'Basket Lifetime'.

The basket of a registered customer's previous session is restored if the


customer returns the storefront in a new session and is recognized by the
system. If a customer logs in, and there is no current session basket, the
basket of the registered customer's previous session is restored.
Otherwise the current session basket becomes the basket of the
customer and the previous basket is provided through the API.

Baskets persistent for all customers

Baskets of registered and anonymous customers are stored for the


duration configured with the preference 'Basket Lifetime'. The basket of a
customer's previous session is restored if the customer returns the
storefront in a new session. If a customer logs in, and there is no current
session basket, the basket of the registered customer's previous session is
restored. Otherwise the current session basket becomes the basket of
the customer and the previous basket is provided through the API.

Customization with Session and Request / Response Handling

In Demandware® based on certain events pipelines are triggered


internally by the system. This allows for adding custom logic for the event
triggers. The pipelines are included in Site Genesis by default. They can
use standard pipeline elements of the storefront including pipeline nodes,
scripts and system pipelets. Since the pipelines are called and executed

©Demandware, Inc. Version Date 11/6/2013 Page 10


Module 4: Application Design
before running the targeted pipeline, template nodes are not used in the
internal pipelines, instead they exit with an end node.

Pipelines Handlers are triggered for the following events:

OnSession-Do: On creation of a session the pipeline OnSession-Do is


called. The pipeline can be used, e.g. to prepare promotion or price books
based on source codes or affiliate information in the initial URL.

OnRequest-Do: The OnRequest pipeline is called with every request to


the storefront. This happens both for cached and non-cached pages.
Remote include template calls will not trigger the OnRequest pipeline, the
OnRequest pipeline is only called once upon the original request.

These pipelines are called often, even for cached pages, for performance
reasons they should be kept very lightweight, for example no complex
logic or database calls should be made in these pipelines.

The session handling and request/response handling are managed


internally in the Demandware® system, although there are ways to
programmatically utilize the session and hook into the request and
response for customizations.

The use cases for these customizations are rare and should be kept
minimal. Do not store credentials or sensitive information on the client
side (for example, via client-side variables or cookies). Also, since the
sessions are stored in the Demandware® platform for failover,
information that should not be saved in the system for security concerns
(for example credit card CVV, customer passwords etc.) should also not
be added to the session.

When storing/setting data into the session, the Demandware® platform


recalculates information for dynamic customer groups and vary By
“price_ promotion” caching. Storing information in the session should
only be done on low traffic pages and a little as possible.

Request Serialization

For one session only one request is processed at a time. All other requests
are held back until the first one finishes. This is called request
serialization. This is done to avoid one user occupying many or all
resources (threads) within an app server. After ~ 20 seconds all requests
are released. This mechanism applies only to pipeline calls.

Best Practices: Examples of what to avoid


 Write in OnRequest all time a cookie value to [Link].

©Demandware, Inc. Version Date 11/6/2013 Page 11


Module 4: Application Design
 Call a pipeline using HTTPClient within the same session.

API Access - Session

The Demandware® session, request and response can also be accessed


through the DW Script API.

The session is accessed using the [Link] object. The session is


assessable using the TopLevel Global object “session” in dw scripts. It can
also be accessed from the pipeline dictionary for pipelines using
“CurrentSession” for use in pipelet configurations, assign and eval
pipelets.

The session can also be used to store custom data that will remain for the
lifetime of the session. There are two types of custom attributes for a
session.

Custom: The standard custom attributes can be accessed using the


“custom” method of the session object. These similar handlings to other
DW script business object that extends the [Link],
although the session object does not extend ExtensibleObject so it
doesn’t require meta data to be defined for the custom attributes. The
data that is stored in the custom attributes of the session remains for the
lifetime of the session, even if the customer logs out of the site.

Privacy: The privacy custom attributes are handled the same as the
custom attributes, although is a separate group of attributes that is
automatically cleared when the customer logs out. When storing any
sensitive information in the session, the data should be stored in the
privacy custom attributes.

Certain rules apply for what and how much data can be stored in a
session:
 All primitive types (boolean, number, string, Number, String, Boolean,
Date) are supported.
 All Demandware® value types (Money, Quantity, Decimal, Calendar)
are supported.
 All other types must not be stored in a session. In particular persistent
object, collections and scripted objects cannot be stored in a session.
 String is limited to 2000 characters.
 There is a 4k size limit for the overall serialized session.

Below is an example of setting and retrieving a string in a session


attribute. The attribute can be created dynamically:
[Link] = “myValue”;

©Demandware, Inc. Version Date 11/6/2013 Page 12


Module 4: Application Design
The newly created attribute “mySessionAttribute” can be read using the
following: var mySessionAttribute = [Link];

API Access – Request / Response

The current request can be accessed by the [Link] object.


This object is available from the TopLevel Global object as “request” in a
DW script or template. It can also be accessed in pipelines through the
pipeline dictionary variable “CurrentRequest”.

The request object provides methods to access the attributes of the


request, including HTTP headers, URL parameters as well as access to set
cookies.

The response can be accessed by the [Link] object. This


object is available from the TopLevel global object as “response” in a DW
script or template.

The response object allows for updating response headers and setting
cookies.

Storing Objects in the database

OCA Handling

Optimistic control attributes are long values stored with each object
being persisted / written into the database. The number is used to detect
parallel object modifications of multiple threads or on different
application servers. Any request to write an object into the database will
fail, if <new OCA> != <old OCA + 1> and throw an OCAException in the
error log which cannot be handled.

Storing Custom Attributes and Localizable Attributes

Custom Attributes and all localizable system attributes are stored in the
database in tables beside the system objects, storing a compound key of
attribute ID, locale and corresponding system object ID. Keep this in mind
while creating object queries with lots of attribute conditions, defining
large amounts of custom attributes etc.

Custom objects are handled the same way, so use them with care!

©Demandware, Inc. Version Date 11/6/2013 Page 13


Module 4: Application Design
Exercise 1 – REST style web service

Task The customer wants to provide a couple of REST web services


enabling several flash applications and native mobile apps to
consume data from DW. Data have to be provided in a custom XML
format for products, deal of the day promotion and customer
profiles (getting gender, first and last name).

Questions/
Points to
Consider

Solution Path

©Demandware, Inc. Version Date 11/6/2013 Page 14


Module 4: Application Design
Lesson 3: Best Practices Designing Pipelines, Templates and
Demandware® Scripts
Objectives:

 Utilize best practices for pipelines, templates and scripts.

It is important to understand the best practices


of coding within Demandware® outside of
using just the correct styling syntax.

Below are some examples of how to develop


code in Demandware®. This is not a full list of
best practices, but examples to help you
understand best practices exist. Then, you can apply a similar thought
process to coding best practices in your custom code.
Pipelines

When designing a Pipeline, each pipeline should consist of one or more


start nodes. It is important to comment/add description to the pipeline as
they are coded to improve readability and maintainability. Use the text
node to describe/explain any complex logic at the top of the pipeline or a
segment of a pipeline which is demanding. From a maintainability
perspective, it is important to document the purpose of the pipeline,
associated inputs, outputs being produced and important parameters
required in the processing of the pipeline.

Pay attention to the Call Mode: Public/Private for every pipeline. Every
pipeline which is not meant to be accessible via a browser request is
marked private e.g. (Job related pipelines and Pipelines called from other
pipelines).The rest can be public. Most projects inherit Site Genesis
Starter code. For this reason it should be obvious not to just overload Site
Genesis but develop starting from Site Genesis and make the required
modifications to its code base.

Huge Pipelines should be broken down for modularity, maintenance &


usability.

Best Practices: Demandware® strongly recommends that when


designing pipelines use the following rules;
 no or only a few database calls
 simple (static) template response
 cache the result page

©Demandware, Inc. Version Date 11/6/2013 Page 15


Module 4: Application Design

Best Practices: Examples of what to avoid;


 Creating wish list for every customer who visits the site.
 Creating an empty basket for every customer who visits the site.
 Misusing the basket by creating and removing line items to calculate
possible promotions for an individual user.

Additionally, the following principles should be practiced:


 Remove or mark as private legacy / unused SG pipelines.
 Use stop node for pipeline termination for Jobs
 Use Pipelet “labels” to make the flow / code readable
 Pipeline in/out/config use of resource files for localization when
doing so, hardcoded values should be made configurable when
appropriate.
 Use correct path and response for each error node of pipelets.
 Hard coded values made configurable when appropriate etc.

Pipeline Error Handling

Best Practices: Use Site Genesis. Projects inherit Site Genesis Starter
code.
 Use proper error handling in pipelines. Error elements for each error
node, correct path and response for each error node of pipelets
 implement error handler within pipelines (start node Error) and the
general error handler Error-Start, make sure evaluating ErrorText and
PipelineName parameters in the pipeline dictionary
 Use stop node for pipeline termination for jobs.

Templates

Some key concepts related to designing a template are;


 Templates for product html can grow large. Break
templates into smaller pieces for better maintenance,
readability and reusability. This helps to identify coding
problems.
 Access text/String through resource bundles so it is localized (no
text hardcoding), create semantic HML.
 No inline CSS or Javascript should be written, make use of the
Demandware® web form framework.

©Demandware, Inc. Version Date 11/6/2013 Page 16


Module 4: Application Design
 Remove unused SiteGenesis ISML templates and/or remove them
from public view, modularize duplicate functions in templates.
 Cache template response within the Demandware® system, usually
done to improve storefront performance. It is critical that each
template defines its own caching strategy, if applicable. Most
storefront pages are read only data and follow some level of
caching. Local includes inherit the including templates cache
strategy. Remote includes define their own cache strategy for
better performance.
 Be aware of caching mechanisms and fallback behavior.
Caching is request specific. If iscache status=“off”
specified, no directive will apply during this request the
smallest caching interval will win.

Demandware® Scripts

Demandware® Script is the server-side scripting language, which is


interpreted by the application server and included in storefront pages as
JavaScript. It is used to add custom processing for data and is associated
to a pipeline.

Best Practices when designing scripts


 ScriptLog is implicitly provided by all script nodes and is used only as
convenience or debug during the implementation. Clean them up
before they make it to production. This could be done during the
build process.
 Name local variables as descriptive as possible.
 Do not log sensitive data in the log files.
 Always test and code for boundary use cases.
 Remove Site Genesis Legacy script folders and files, if not used.
 Script folder filename, input / output parameters follow naming
conventions as outlined by Demandware® coding style guide.
 Scripts code validate input and output parameters.
 Avoid large script blocks in templates, as this cannot be debugged
and might be the cause for large template processing time without
any chance to drill down into details.

When designing Demandware® Scripts, have the differences to Java in


mind, such as
 Be aware of JavaScript variable scopes, think about closures.

©Demandware, Inc. Version Date 11/6/2013 Page 17


Module 4: Application Design
 Use conditional catch statements to handle expected errors.
try { ... } catch( e if e instanceof IOError ) { ... }
 Make sure you understand E4X (ECMAScript for XML), which is a
nice and simple pattern to implement e.g. XML REST web services.
 Implement wrapper classes, where necessary or helpful, use
techniques to delegate function calls to more generic
implementations using the apply-method.
 __noSuchMethod(), no Proxy class implementation currently in
Rhino

Think about inheritance, but keep in mind Demandware® does not


support a way to extend existing API classes, so it might be useful to wrap
around.
[Link]

This approach is not easy to debug in the Demandware® Studio script


debugger, but defining a debug variable and just assign this is quite
helpful.

©Demandware, Inc. Version Date 11/6/2013 Page 18


Module 4: Application Design
Lesson 4: Coding Best Practices - Modularize Code and
Implement Stable, Well-defined Interfaces
Objective:

 Identify coding best practices for modularization.

When designing code for Demandware®, it is


important to keep code modularized to share
repeating code blocks to reduce the overall
code base and improve code maintenance
efforts.

When modularizing code, interfaces are created to help define the proper
input and output parameters of code, code should also validate Object
Type, Min/Max length, Min/Max value, Null/empty value etc.

Modularity and associated interfaces are achieved in many ways


including:

DW Script Libraries

It is a good practice to create DW Script libraries to hold generic functions that


can be used throughout the site for common functionality. To avoid
overwriting functionality please make sure to use name spaces and class
hierarchies. There are include functions that are used in DW scripts, pipelines
and templates. The script functions should define and validate the correct
input is being provided from the calling code.

An example of a script library is functions for helping with string manipulation.


This is a script file that holds functions to help manage JSON strings called
“[Link]”

The [Link] script file contains functions like the following:

function escapeJsonString(s : String)


{
// Validate input parameters and code to perform function
return sb;
}

Pipeline Call Nodes

Separating common functionality in pipelines into smaller re-usable


pipelines is the best way to allow maintenance and readability of

©Demandware, Inc. Version Date 11/6/2013 Page 19


Module 4: Application Design
Demandware pipelines. As visual programming with pipelines introduces
complexity and not all the time allows easy understanding of the involved
script and template code, which is opaque behind the “boxes”, pipelines
should be named correctly and broken into pieces. Therefore, any kind of
private sub-pipelines or private helper pipelines should be created for
encapsulation, providing a quick documentation per start node. These
smaller pipelines then are referenced by using a pipeline call node.

Sub pipelines should use name end nodes to allow a good level of
response handling utilized at the call node to address different return
states.

Template Modules and Remote Includes

Modularized code is created in templates using:


iscomponent: The iscomponent isml tag is used to include the contents
and output of another pipeline in a template.

Best Practice: Using iscomponent is a best practice over using


“Remote Includes” since the intent of the include being remote (as
opposed to local) is clearer and it includes custom input parameters to
help define an interface.

<iscomponent pipeline ="Product-Show" productid="1234" name="Wide-


screen television">

ismodule: The ismodule component is similar to “Local Includes”, where


the calling code is a local template (which shares the same pipeline
dictionary, caching policy of the caller). Since a custom name is created
for the module when called, the intent of the module is very clear to the
developer using the module.

<isproducttile product="${product}" showswatches="${true}"


showpricing="${true}"/>

Cartridges

Separate adapters to third party systems, BM plugins or import logic into


individual code libraries/cartridges. Another use case is separation of
code which is used in different security contexts such as BM or storefront
functionality.

©Demandware, Inc. Version Date 11/6/2013 Page 20


Module 4: Application Design
Lesson 5 Object Quotas
Objectives:

 Explain quotas.
 Define Quota types and best practices.
 To Architect a solution that can safely operate on Demandware.

The Demandware® Platform is designed to be


used as an ecommerce system. With the usage
scenario in mind, certain constraints and limits
are set during design and implementation to
ensure the efficiency and stability of solutions
built on top of the platform. These limits
concern memory usage, resource consumption, API calls, and the number
of business objects.

Quotas are defined as explicit usage controls (quotas) for Script and
Pipelet API calls (frequency), and Objects (per-instance) are derived from
implicit technical limits. Quotas define programmatic boundaries under
which custom implementations can safely operate on Demandware.
Platform resources include memory, application server threads, database
table sizes, and so on. Typically, when a quota is exceeded, custom code
is using platform capabilities inefficiently, and a more efficient solution is
possible.

Explicit usage controls (quotas) provide quantitative, measurable, and


enforceable standards for product usage. Explicit controls (quotas) are
the only way to ensure safe-use in scalable way; vs. relying on deep
product knowledge. Mutually assured API/Object usage is essential to
Demandware, and is a prerequisite for achieving 100% compatibility
across global releases. It preempts harmful usage practices and the
resulting negative consequences.

©Demandware, Inc. Version Date 11/6/2013 Page 21


Module 4: Application Design

Figure 2: How Scalability of a Demandware system is impacted

Today, platform users can inadvertently exceed usage limits; typically via
a direct misuse of an API or Object. For example:
 A very inefficient usage is when a more resource-
efficient implementation method exists for the same
functionality.
 An abuse of the platform is trying to derive functionality
for which the platform was not designed.

Exceeding usage limits will result in unintended platform state changes,


and service disruption for that unique realm. Forms of unintended
platform state changes include AS process thread exhaustion, and AS
process failure;
 AS thread exhaustion = AS process becomes slow –
Request WAITS
 AS failure – likely from OOM conditions – AS Cluster is
minus 1 AS until restarted

Platform instability has the most significant negative impact on the


performance on a Demandware Realm. Negative effects at the Realm-
level include:
 Slow response time for Sites and tools (BM)
 Inconsistent Site functionality (job failure)
 Site(s) instability (extreme: intermittent unavailability)

Example – ‘Bad Practice’ #5 - Sorting of large number of objects in


memory when creating feeds for external systems

©Demandware, Inc. Version Date 11/6/2013 Page 22


Module 4: Application Design
What is a quota?
A quota governs the usage of an aspect of the platform to be within safe
boundaries by defining limits. They are part of Demandware API
specifications. The following is the behavior of exceeding quota limits;
 WARN threshold (usually 60% of limit), a quota warning
is logged.
 ERROR threshold (100% of limit), a quota exception is
logged.
 Quotas with limit “0” have no WARN threshold

What happens when a quota is exceeded?

A quota is either "enforced" or "not enforced." If an enforced quota is


exceeded, an exception is thrown, which prevents the current operation
from completing. The exception cannot be caught within the
customization. The design criteria must be avoidance of quota violations.

Examples for quota violations are:


 A Collection with too many elements created in memory
for one request, or
 Too many persistent objects of a certain type are
created in an instance.

If an enforced quota is exceeded in a storefront request, the general error


page appears. If an enforced quota is exceeded during a standard import,
a Data Warning or Data Error is reported. If a quota is not enforced, the
platform does not take an action when the limit is exceeded.

Demandware® plans to enforce all quotas in the future.

How "safe" is my implementation?

Information on API and object usage levels, number of violations on a


particular instance, and which quotas are enforced, can all be found in

Business Manager >Administration > Operations > Quota Status).

Business Manager shows quota usage/violations since server restart or


within the last 24 hours.

Some quotas specify a warning threshold, to give you an early indication


that a quota limit may soon be exceeded

©Demandware, Inc. Version Date 11/6/2013 Page 23


Module 4: Application Design

Figure 3: Object Quota overview in Business Manager

When the warning threshold is exceeded and when the quota limit is
exceeded, messages are written to the quota log files. This happens for all
quotas, enforced and unenforced. The log files are written to the log files
folder and have the prefix "quota". Quota log files are written with a time
delay. The log files contain information about where the quota violation
occurred. Also, they may contain information about quotas that do not
appear in Business Manager.

Quota Types

Memory

Memory related quotas are intended to avoid extensive use of memory


consumption, such as:
 [Link] (20k)
 [Link] (1000k)
 [Link] (200)

Read-only Storefront

Read-only quota are intended to leverage caching of system objects in an


optimal way avoiding complex synchronization between application
server instances, therefore such quotas do not allow object manipulation
from storefront code. Examples for such quotas are :
 [Link]@SF (0)
 [Link]@SF (0)
 [Link]@SF (0)

Other object types can be manipulated from storefront:


 Nonstageable custom objects
 Basket, Customer related data or Inventory

©Demandware, Inc. Version Date 11/6/2013 Page 24


Module 4: Application Design
No file creation is allowed in storefront code, it would require
synchronization on file system level:
 [Link]()@SF (0)
 [Link](File)@SF (0)

API to handle consumer created content:


 [Link](
callback: Object)
 [Link]()

No triggering of job-like processes is allowed from storefront:


 [Link]()@SF (0)
 [Link]@SF (0)

Object Quotas

Object quotas and object relationship quotas define a limit on the


number of objects. Object quotas typically limit the number of objects of
a particular type per Demandware® instance. Object relationship quotas
limit the number of objects that are associated with one object of that
type.

Supported number of objects per instance (PO quotas)


 [Link] (100)
 [Link] (400k)
 [Link] (400k)

Supported number of relations per object (relation quotas)


 [Link]-
LineItemPOs (20)
 [Link]-
AssignmentPOs (1000)

Additional Types

Other quotas are including any kind of other effects which might impact
platform stability, e.g.:
 Prevent high database churn / processing
 [Link]()@SF
(0)
 [Link]()@SF (10)
 [Link] (10 - unenforced)
 Other
 [Link]@SF (300sec)

©Demandware, Inc. Version Date 11/6/2013 Page 25


Module 4: Application Design
 [Link]()@SF (8)

Quota Overrides

Quota overrides are a mechanism to soften (unenforced) quotas, mainly


for realms created before 10/2011. Wherever possible customers should
work without overwrites. Some rules apply to overrides:
 Setup by Demandware for Primary Instances
 Setup by Users for Sandboxes (via Site Import)
 Demandware will never unilaterally remove Quota
Overrides
 Request temporary Quota Overrides via support ticket
(if impact would justify a SEV-1)

©Demandware, Inc. Version Date 11/6/2013 Page 26


Module 4: Application Design
Exercise 2 – Code Design Lab

A developer has created a piece of code that allows storefront users to


subscribe to mailings for each brand available in the storefront. The
subscription data is stored in custom objects which can be exported for
use in an external E-mail marketing system.

Imagine you are the responsible architect and perform a code review of
this developers work – identify any bad practices or problematic logic.

©Demandware, Inc. Version Date 11/6/2013 Page 27


Module 4: Application Design
Lesson 6: Logging
Objectives:

 Identify best practices for logging.

A valuable way of debugging run-time issues in production where setting


debuggers is not possible is logging system performance data. However,
logging large amounts of data all the time to text files
 degrades system performance and
 creates monstrously sized log files whose utility is compromised by
the sheer volume of data present in them.

To balance the need to debug run-time systems with the need to have
highly performing systems with small, focused log files, Demandware®
has created an extensive logging facility based around the
[Link] class:

There are 5 Categories of Log Categories that are generated from code;

 Fatal - always written to log files; can be used to send email messages
when certain conditions arise
 Error - always written to log files - should not be used for debugging in
production since extensive writing to log files can have performance
impacts
 Warn - always written to log files
 Info / Debug - only written to log files for 10 minutes after enabled in
BM - useful for specific case testing.
 Always use logging categories, nested diagnostic context (NDC) and file
prefixes for custom logs.

Note: Custom logs have file size limitations.

Generating a message to the log file can be as easy as including a line:

[Link](“Entering Tax Calculation Routine”);

To make log files more readable it makes sense to create a log category
first making sure log messages contain contextual information. This can
be done using:

[Link](category)or
[Link](prefix, category)

©Demandware, Inc. Version Date 11/6/2013 Page 28


Module 4: Application Design
These tools are easy to use and most developers incorporate them readily
into their code. However, there is a more sophisticated logging
mechanism available to developers who wish to produce rich logs for
certain areas of the code at certain times.

The [Link] (Nested Diagnostic Context) is very useful for


providing a context for which log entries are generated. As the name
implies, these contexts are nested so a developer can enable logs for all
‘product’ related issues for instance, or, if that produces too verbose a log
stream, more granular contexts (such as [Link] or
[Link] or [Link]) can be created.

These contexts, combined with the ability to specify severity, are then
specified in the Business Manager (under Operations->Log Settings) so
that only log entries of a particular severity for a particular subsystem are
written to file.

The effect of this is that code is written with the intent of having
extremely verbose run-time information available but only on-demand
and only for very narrow areas of the code. This is a critical real-time
debugging tool for problems that appear only in production, but not in
the test sandboxes.

Cleaning up Log Files

Prior to any go-live, all Error Logs are clean under normal operations.
Since all FATAL, ERROR, and WARN errors are logged to the system log
files, these files can be multiple Mega-bytes, or even Giga-bytes per day.
This is bad because it affects the system performance and it makes
filtering the log files while looking for specific behaviors difficult.

The errors that clog Error Logs are often null-value exceptions; typically
some piece of code is trying to access a child attribute of a non-existent
parent. These are most often cleaned up by putting null-checks around
the data access.

Several tools are developed to process error logs. One of the most useful
is the following UNIX/OsX/Linux/Cygwin shell command which
aggregates, counts, and ranks all the errors in a set of error-blade files:

grep -h -e "^\[" error-blade* | sed -e "s/^[^\"]* \"//g" | sort | uniq -c |


sort -r > [Link]

This is very valuable for helping find and prioritize errors in the log files.

©Demandware, Inc. Version Date 11/6/2013 Page 29


Module 4: Application Design
Lesson 7: Best Practices - Data Usage Drives Optimal Data
Storage
Objective:

 Learn about places to store information about the shopping behavior


of a customer.
 Identify the best use of Custom Objects.

Information is stored in the DW system in


several ways and for many reasons. Some of
the most important aspects of designing code
in DW is to evaluate if DW ecommerce
platform is the proper place to store this
information and is aligned with the intended
use of the platform also understanding the quota / performance
implications of each type of storage context, as well an understanding of
state and lifetime of the storage methods.

Custom Objects

Custom objects are a powerful feature of the DW platform that is used to


extend beyond the system objects in a persistent manner.
It’s important to understand that although custom objects are useful,

Example: Order Management System is the proper place for


legacy order information to reside and should provide a web
service that DW can call for display of real time data.

Example: customer email list / subscription data, the DW site can


capture email signups and un-subscribes, but should report that
data in real time to an outside or third party system that is
intended to manage specific logic related to email campaigns, as
opposed to storing this data in DW in custom objects.

they should only be used for purposes for the intended use of the e-
commerce storefront. Especially if the data set grows predictably over
time.

The common use case is to store legacy order history or customer email /
subscription data in custom objects. These types of data sets are more
suited for outside systems that are called by the DW system in real time.

©Demandware, Inc. Version Date 11/6/2013 Page 30


Module 4: Application Design
Think about lookup frequency, quota, and usage pattern.

There are valid use cases for using custom objects for data in the

Example: Take Omniture, each template for the site


needs to be tagged with specific client side JavaScript
that reports data to Omniture based on the page. This
data is managed directly in the templates but having
Business Manager access to the JavaScript allows an
Omniture administrator (who may not have access to
DW studio) adjust the client side JavaScript for each
page of the site.

storefront. Using custom objects to store small, temporary data sets or


data that is managed by a Business Manager user. One common use case
for custom objects for configuration purpose's is analytics integrations.

In this case, a custom object record is created that holds the client side
Omniture JavaScript for each related template on the site, with the
template name as the “key” for the custom object.

This is an example that utilizes custom objects to extend the existing data
model that will not result in the amount of objects totaling over the quota
limit (400,000 total custom object records). It does not affect storefront
performance since only one custom object record is used per template
request and allows the custom object look up to be based off the object
key instead of a custom object search

Demandware® Session

Another way to store information in DW is in the current session for the


user. The session storage is useful for state that is only related to the
customer and the current session.

Storing data in the session should be kept minimal due to the overhead
and short persistence of the storage.

Some aspects of session related storage to keep in mind is that session


data is actually written to disk due to serialization of the session for fail-
over.

©Demandware, Inc. Version Date 11/6/2013 Page 31


Module 4: Application Design
This is useful to create customer groups and personalize experience.

Client-side Cookies

Example: A valid use of cookies is to write a cookie to the


browser for geolocation. When the geolocation of the user is
found to present a region specific page to the customer,
cookies can be set to prevent further unneeded calls to the
geolocation service to find the location of the user on every
request.

Cookies are a convenient way of storing site data for information that
extends beyond the session. Although the amount of data stored in a
cookie is limited by nature. Use for information required for every
request server side, set useful expiration dates. DW does store cookies by
default and those cookies are not accessed or manipulated pragmatically
as they are use internally by the system. For example, accessing of
changing the DW internal session cookies can cause issues with the
platform.

Best Practice: It is recommended to instead set a cookie with the


user’s locale to be used by subsequent requests.

Best Practice: Do not overwrite/modify dw_cookies.

HTML 5 Storage Techniques


With HTML5, web pages can store data locally within the user's browser
which is similar to cookies, but have some fundamental advantages over
cookies:
 The data is only utilized, as opposed to cookies which are included in
every web request, which has less overhead on the requests.
 Cookies hold only a very limited amount of data. HTML 5 web storage
allows for large data sets (typically 5 MB) that are quickly accessed.
 Most modern browsers now have support for web storage (as of IE 8
etc.)

Web storage allows for local storage (persistent) and


session storage which is used on a window bases as
opposed to domain based cookies.

©Demandware, Inc. Version Date 11/6/2013 Page 32


Module 4: Application Design
Exercise 3 – Sale Product Store

Task Customer has various storefront sites and wants to show only sale
products in one of those sites. Sale products are being identified
using a custom attribute.

Questions /

Points to
Consider

Solution Path

©Demandware, Inc. Version Date 11/6/2013 Page 33


Module 4: Application Design
Exercise 4: Multiple Currencies

Task A customer runs a worldwide shop system within one single site and
wants to show product prices in different currencies based on the
country the customer comes from.

Questions /

Points to
Consider

Solution Path

©Demandware, Inc. Version Date 11/6/2013 Page 34

You might also like