67
DEV364 Caching Best Practices in .NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Embed Size (px)

Citation preview

Page 1: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

DEV364

Caching Best Practices in .NET Applications

Ron JacobsProduct ManagerMicrosoft Patterns & Practices

Page 2: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practices

Begin with the Architecture

Choose the right caching technology

Cache to avoid hops

Manage your cache well

Use the caching application block

Page 3: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practice #1:Begin with the Architecture

Know why you are caching

Know what you are caching

Know how the data is accessed

Page 4: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Know why you are caching

PerformanceKeep the data close to the consumerMinimize data access – remote or disk

Trade OffPerformance vs. Cache OverheadCache misses are expensiveCaches consume resourcesPoorly implemented caches hurt performance more than they help

Page 5: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Know why you are caching

Scalability Data access is often the limiting factor

Scaling out without caching often makes the problem worse

Reducing data access eases demand on the server

Adding caching to expandable tiers improves scale

Trade OffSolution Complexity vs. Simplicity

Page 6: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Know why you are cachingAvailability

Loosely coupled systems have different availability challengesProvide some level of functionality when other systems are off-line

Trade OffComplexity vs. SimplicityComplex data managementComplex security requirementsNo longer Request / Response protocol

Page 7: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Know what you are caching

Lifetime Permanent, Process, Session, Message

Logical Scope Application, Business Process, Role,

User

Physical Scope Organization, Farm, Machine, Process, AppDomain

Staleness

Change Characteristics

Tolerance

Transformation Pipeline

Raw, Processed, Rendered

Page 8: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Lifetime

Lifetime is the time period during which state is valid

Permanent state Persistent data used in an application

Example – data stored in the database

Process state Valid only for the duration of a process

Example – temporary filename

Page 9: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Lifetime

Transaction stateValid for the duration of a transactionExample – Order submitted to OLTP system

Session state Valid for a particular user sessionExample – Shopping cart in ecommerce site

Message state Exists for the processing period of a messageExample – Processing a message sent to a web service

Page 10: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Physical Scope

Physical scope is the physical location from which the state can be accessed.

Organization Accessible from any application within an organization

Example – Active Directory information

Server Farm Accessible from any computer within an application farm

Example - Hit count on a web site

Page 11: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Physical Scope

Machine Shared across all applications on a single computerExample - Registry data

Process Accessible across multiple AppDomains in a single processExample - Authentication tokens

AppDomain Available only inside a single AppDomainExample – Static variables

Page 12: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Logical Scope

ApplicationValid within a certain application

Business ProcessValid within a logical business process

RoleAvailable to a subset of users

UserAvailable to a single user

Page 13: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Staleness

State staleness is the difference between the master state and the cached state.

Volatility Highly volatile master state makes caching difficult

Relevancy of changes It is possible that master state changes will not have an adverse affect on the usability of a process

Example: Changing a Web page style does not affect the business process operation

Page 14: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Staleness ToleranceTolerance: The effect of the staleness of state on the business process No tolerance

Transaction stateExample: Banking system is using a customer balance to approve a loan, the balance must be guaranteed to be 100 percent accurate and up to date.

Some tolerance There are cases where a known and acceptable period for updating the cached items is acceptable Example: An online catalog displaying banking products available upon completion of an application form

Page 15: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

State Transformation

Data is often transformed from raw formats to consumable formats

Cache is consumable format when possible

Page 16: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Know how the data is accessed

1,000,000 users accessing 10 recordsProbability: High cache hit ratio

10 users accessing 1,000,000 recordsProbability: High cache miss ratio

What indexes are required?Example: search by name, ID or region

Is the same data likely to be accessed repeatedly? Over what time period?

Page 17: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practice #1:Begin with the Architecture

Know why you are caching Know what you are caching Know how the data is accessed

Knowing the requirements is crucial to getting the caching solution right

Page 18: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practice #2:Choose the right technology

Caching technologies in .NET are built to handle specific requirements

Requirements can be expressed in terms of state attributes

Map your requirements to the appropriate caching technology

Page 19: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Cache Storage

Memory Resident CacheSmall data sizeRepeated accesses over a short period of time

Disk Resident CacheHandling large amounts of dataAccess may involve disk I/OSource is not always availableState lifetime must exceed process or machine lifetime

Page 20: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Cache Item Expiration

Controls item lifetime - often policy basedProgrammatic

Cache.RemoveItem(“Item 1”);

Absolute time Item expires at 12:00

Sliding timeItem expires in 1 hour

DependencyItem 1 expires when item 5 expires

Page 21: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Notification based expiration

Page 22: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Cache Flushing

Caches must not grow indefinitelyFlushing provides a way to be smarter about item managementScavenging based on access may reduce resource utilization while preserving hit ratio

Page 23: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Cache ScavengingRemoves seldom used items

Least Recently Used (LRU) Flushes the items that have not been used for the longest period of time

Least Frequently Used (LFU)Flushes the items that have been used least frequently since they were loaded

Priority Application code decides priority

Low priority items flushed first

Page 24: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Cache Monitoring / Tuning

Monitor the cache to measure the effectiveness of the solution

Provide controls for cache tuning

Cache Size Measure of resource consumption

Cache Entries Number of items in cache

Hit / Miss ratio Overall effectiveness of cache

Turnover the number of insertions and deletions

Insert Time How long it takes to store

Retrieve Time How long it takes to read

Page 25: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

.NET Caching Technologies

ASP.NET Cache

ASP.NET Session

ASP.NET Application

Remoting Singleton

Memory-Mapped Files

Microsoft SQL Server 2000 or MSDE

Static Variables

ASP.NET Client Side Caching

Internet Explorer Caching

Enterprise Services Object Pools

Build your own

Page 26: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Cache

Advanced web caching with ASP.NET

Use directly through API or indirectly Page directives

Physical Scope AppDomain

Logical Scope Site / Application

Lifetime AppDomain

Management Expiration, Dependencies, Notifications

Page 27: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Cache Tips

Use CacheItemRemovedCallback event to refresh cached items

Set Item Expiration and Priority when adding cache items

Cache items may have file dependencies – source XML file for example

ASP.NET Cache Can be used for other types of applications but test, test, test.

Page 28: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Session

Created per-user session

Provides simple name/value pairs

Physical Scope AppDomain, Machine, Farm

Logical Scope User

Lifetime AppDomain*

Management None

Page 29: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Session Tips

Can be configured for three modes of operation:

InProc (Aspnet_wp.exe)

StateServer (Aspnet_state.exe)

SQLServer – Uses TempDB

For persistent SQL Server mode see http://support.microsoft.com/default.aspx?scid=kb;en-us;311209

Page 30: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Application

Provides application (site) wide cache

Provided for backward compatibility

Physical Scope AppDomain, Machine, Farm

Logical Scope Application (site)

Lifetime AppDomain

Management None

Page 31: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Application Tips

Use sparingly, ASP.NET cache is a better choice

Objects stored in Application state must be thread safe and thread agile

Application state is not shared across processes or machines

Page 32: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Remote Singleton

Implementation of the Singleton pattern accessed using .NET Remoting

Physical Scope Farm

Logical Scope Application

Lifetime Machine

Management Build your own

Page 33: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Remote Singleton Tips

Override InitializeLifetimeService and return null for an infinite lifetime

Poor performance (caused by serialization) and the lack of scalability it produces mean that this choice is often misguided.

Remote caching is typically done better with SQL Server

Page 34: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Memory Mapped File

Enables multiple processes dynamically accessing shared memory using file mapping Win32 API

Physical Scope Machine

Logical Scope Application

Lifetime Machine

Management Build your own

Page 35: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

SQL Server

Common development model

A powerful choice when data persistency is critical

Physical Scope Organization

Logical Scope Application

Lifetime Machine

Management Not cache specific

Page 36: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Static Variable

Good candidate when no cache-specific features are required.

ASP.NET cache is based on static vars.

Physical Scope AppDomain

Logical Scope Application

Lifetime AppDomain

Management Build your own

Page 37: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Enterprise Services Object Pools

Cache of objects hosted in a pool

Useful for objects which are expensive to construct

Physical Scope Farm / Process

Logical Scope Application

Lifetime AppDomain / Process

Management Component Services

Page 38: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

ASP.NET Client Side Caching

Mechanism Recommended uses

Hidden fields To store small amounts of information for a page that posts back to itself or to another page when security is not an issue. You can use a hidden field only on pages that are submitted to the server.

View state To store small amounts of information for a page that posts back to itself. Using view state provides basic security.

Hidden frames To cache data items on the client and to avoid the roundtrips of the data to the server.

Cookies To store small amounts of information on the client when security is not an issue.

Query strings To transfer small amounts of information from one page to another when security is not an issue. You can use query strings only if you are requesting the same page or another page using a link.

Page 39: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Considering Caching in Distributed Applications

((11 ( (Define the needDefine the need:: - Performance?- Performance? - Scalability?- Scalability? - Availability?- Availability?

(2( Map the application’s (2( Map the application’s data entities state data entities state attributes.attributes.

(3( Refer to the “Caching (3( Refer to the “Caching Architecture Guide forArchitecture Guide for .NET Applications” to.NET Applications” to match the requirementsmatch the requirements for a technology.for a technology.

Page 40: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practice #3:Cache to avoid hops

Caching can be handled at the various layers of your architecture

Cache the most transformed view of your data when possible

Avoid cross process / cross machine calls whenever you can

Page 41: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Considering Caching in Distributed Applications

Page 42: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching in UI Components

ASP.NET pages

ASP.NET page fragments

Windows Forms controls with a long render time

Example: TreeView controls

Personalization data

Page 43: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching in UI Process Components 1. UI components make a

request for data from the process components.

2. The UI process component checks if a response is present in the cache and returns it.

3. If the requested data is not cached the UI process components delegate to the business layer elements and place the response in the cache.

Page 44: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Business Entities• Transforming

unstructured data to entities is expensive

• Caching business entities saves transformations

• Use timestamps notifications and expirations to avoid stale data

Page 45: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Business Entity Factory Pattern

• Delaying transformation until needed is a good idea

• Cache unformatted data

• Transform to entities when needed

Page 46: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching in Service Agents

• Cache only non-transacted data

• Improves scalability and availability when service is slow

• Set caching policy by service

Page 47: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practice #4:Manage Your Cache well

Be smart about loading your cache

Consider your loading strategyProactive

Notification or Pull

Reactive

Synchronous or Asynchronous

Page 48: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Cache Loading

Proactive LoadingLoad at the start of the process

AdvantageYou know what is in the cache

DisadvantageYou may be caching data that you don’t need

Startup time will be impacted

Page 49: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

When to use Proactive Loading

You are using static or semi-static state that has known update periodsYou are using state with a known lifetimeYou are using state of a known size. If you use proactive cache data loading when you don’t know the size of the data, you might exhaust system resourcesYou have problematic resources, such as a slow database, a slow network, or unreliable Web services.

Page 50: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Proactive Loading Example1. Based on a schedule or

other type of notification, a dispatcher queries application services for their data.

2. Return values from the service agents are placed in the cache, and possibly aggregated with other data.

3. The application queries the cache for subsets of data and uses them.

Page 51: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Notification Based Loading

1. Cache manager subscribes to data notifications

2. Services notify cache manager new data is available

3. Cache manager pulls data from service OR new data is passed as part of the notification

Page 52: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Notification Based Loading

AdvantagesMinimizes state staleness

Application services handle the notifications eliminating the need for a refresh mechanism

Notification-based loading can ensure that multiple caches remain synchronized.

Page 53: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Notification Based Loading

DisadvantagesMany services do not implement notification mechanisms

The application services layer may need more maintenance than when using other loading mechanisms

Implementing notification-based loading can be more complex than using pull loading techniques.

Page 54: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Data Reactively

Retrieve data as it is requested by the application and cache it for future requests.Advantages

Minimizes cache resource utilization

DisadvantagesChecking for existence can make first access slower than without cache

Page 55: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Best Practice #5:Use the Caching Application Block

Static, MMF and SQL storages

Absolute, Sliding and Extended format expirations.

Encryption and Signing of items.

LRU, LFU and Priorities scavenging

Page 56: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Caching Application Block

demodemo

Page 57: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Summary

Caching isn’t something you use to compensate for bad design.

Caching is about managing state.

Choose your caching technology carefully.

Page 58: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Architecture GuidanceMicrosoft patterns & practices

ProvenBased on field and partner experience

AuthoritativeBest advice available

AccurateTechnically validated and tested

ActionableProvide the steps to success

RelevantAddress real world scenarios

Available online http://www.microsoft.com/practicesBooks available fromhttp://shop.microsoft.com/practices

Page 59: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Sharing Code through CommunityGotDotNet Workspaces

Community Blocks

Workspaces for blocks Community Blocks Share ideas / extensions File bugs, fix them too!

GotDotNetMicrosoft

Blocks

Internet

Page 60: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Next Steps

Use patterns & practicesDownload & Use Application Blocks

Participate in Workspaces

Provide us with your feedback:Are we focused on the topics you need?

What other suggestions or requests do you have? [email protected]

http://msdn.microsoft.com/practices

Page 61: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Community Resources

Community Resourceshttp://www.microsoft.com/communities/default.mspx

Most Valuable Professional (MVP)http://www.mvp.support.microsoft.com/

NewsgroupsConverse online with Microsoft Newsgroups, including Worldwidehttp://www.microsoft.com/communities/newsgroups/default.mspx

User GroupsMeet and learn with your peershttp://www.microsoft.com/communities/usergroups/default.mspx

Page 62: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

evaluationsevaluations

Page 63: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

© 2003 Microsoft Corporation. All rights reserved.© 2003 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.

Page 64: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Performance Comparisons

Page 65: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Performance Comparisons

Page 66: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Performance Comparisons

Page 67: DEV364 Caching Best Practices in.NET Applications Ron Jacobs Product Manager Microsoft Patterns & Practices

Performance Comparisons