SlideShare a Scribd company logo
The Top 5
Things You
are doing
today to
hinder
scalability
Dan Wilson
Who is Dan
Wilson

Runs ChallengeWave.com,
Datacurl LLC and NCDevCon

Technical Owner of
Scholastic.com, Lead
Architect of Forum Group

Owner of Model-Glue

Dad of 2, Husband to 1

Loves all things technical
and a good debate
Our Top 5 List
1.Monolithic Design
2.Mis-identification/Misuse of shared
resources
3.Over-reliance on Shared Scopes
4.Stupid Developer Tricks
5.Failure to design for cacheability
Monolithic Design
Credit: http://thecodelesscode.com/case/33
Solution: Partition Databases
Solution: Decouple Functionality
Top5 scalabilityissues withappendix
Shared Resources
Scalability Curve
Fun With Math
Cost of WebServer File
Web Server Thread
+ Network to File System
+ Disk Wait Time
+ Disk Seek Time
+ Transfer time to Webserver
+ Transfer time to complete HTTP Request
______________________
Total Time
Cost of 1 ColdFusion File
Web Server Cost
+ Network Cost to CF Server
+ CF Parsing or Classloading Time
+ Thread Wait time
+ Thread CPU time
+ Transfer time for CF buffer to Webserver
______________________
Total Time
Cost of ColdFusion File With Query
Web Server Cost
+ ColdFusion File Cost
+ Number of Queries ( Network time to DB + Query
Execution Plan + Query Execution + Disk Wait + Disk Seek )
+ Network time to transport result set to CF
+ CF Parsing Time
______________________
Total Time
Types of Shared Resources
● Memory, CPU, Disk Space
● Disk Transfer (Databases!!)
● JVM Space
● ColdFusion template cache
● ColdFusion Threads
● Network Traffic
● Database
DANGER! DANGER!
Over-reliance on Shared Scopes
● Session Scope use is the largest culprit
● Sometimes you have to deoptimize a few
operations in order to provide a scalable
solution (like stop caching a state query in application)
● If you want to use a shared scope and want to
keep an eye on scalability later, use a lookup
factory.
<cfcomponent>
<cfset variables.instance = structNew() />
<cffunction name="init" returntype="CurrentUserLoader" output="false"
access="public">
<cfargument name="Transfer" type="any" required="true"/>
<cfset variables.transfer = arguments.transfer />
<cfreturn this />
</cffunction>
<cffunction name="destroy" output="false" access="public" returntype="void" >
<cfset cookie.userID = "" />
<cfset structDelete( cookie, "userID") />
</cffunction>
<cffunction name="load" output="false" access="public" returntype="any" hint="">
<cfset var loggedInUserID = 0 />
<cfif structkeyExists(cookie, "userID")>
<cfset loggedInUserID = cookie.userID />
</cfif>
<cfreturn variables.transfer.get("User", val( loggedInUserID ) ) />
</cffunction>
<cffunction name="set" output="false" access="public" returntype="void" hint="">
<cfargument name="user" type="any" required="true"/>
<cfset cookie.UserID = arguments.User.getUserID() />
<cfset cookie.Email = arguments.User.getEmail() />
</cffunction>
</cfcomponent>
Avoiding Server Shared Scopes
Stupid Developer Tricks
● Looped Queries
● Lazy-Man Pagination
● ScheduledTask-o-rama
● Database Abuse
Problem: Query in Loop
<cfloop query="OldLastLogins">
<cfquery name="UpdateUsers" datasource="#datasource#">
UPDATE Users
SET Active = 0
WHERE UserID = #OldLastLogins.UserID#
</cfquery>
</cfloop>
Solution?: SQL IN Statement
<cfquery name="UpdateUsers" datasource="#datasource#">
UPDATE Users
SET Active = 0
WHERE UserID IN #ValueList(OldLastLogins, UserID)#
</cfquery>
Top5 scalabilityissues withappendix
Solution: Joins
<cfquery name="UpdateUsers" datasource="#datasource#">
UPDATE users
INNER JOIN lastlogin ON users.userID = lastlogin.userID
SET Active = 0
WHERE lastlogin < now()
</cfquery>
Solution: Joins
<cfquery name="UpdateUsers" datasource="#datasource#">
UPDATE users
INNER JOIN lastlogin ON users.userID = lastlogin.userID
SET users.lastLoginDate = lastlogin.createdDate
WHERE lastlogin < now()
</cfquery>
Problem: EntityToQuery
<cfscript>
EntityToQuery(
EntityLoad("Users",
{ Gender = arguments.genderID}
)
);
</cfscript>
Example: Get Poll Answers
<cfset PollAnswers = entityLoad("PollAnswers",
{
PollID=entPoll[1].getPollID()
}, "")>
<cfif (isArray(Poll) AND arrayLen(Poll) GT 0)
AND (isArray(PollOpt)
AND arrayLen(PollOpt) GT 0)
AND (isArray(PollAnswers)
AND arrayLen(PollAnswers) GT 0)>
Poll Net Result
JDBC
Recordcount: 87,923
Query Time: 14,290 ms
All that for an
ArrayLen() GT 0!
Solution: Query
<cfquery name="LoadGenderUsers" datasource="#datasource#">
SELECT UserID, UserName, Email, GenderID
FROM Users
WHERE GenderID = '#arguments.GenderID#'
</cfquery>
Problem: Lazy Man Pagination
<cfoutput query="GetParks"
startrow="#StartRow#"
maxrows="#MaxRows#">
#ParkName#
</cfoutput>
Solution: SQL
MySql, PostgreSQL: LIMIT, OFFSET
SQL Server: TOP, ORDER BY
ORACLE: WHERE rownum <= 10
Problem: No Encapsulation
<cfif qExists.idexists>
<cfquery name="qUpdate" datasource="#somedatasource#">
UPDATE tblKalendarCategories
SET CategoryName = '#form.CategoryName#',
CategoryTextColor = '#form.CategoryTextColor#'
WHERE CategoryID = #form.CategoryID#' />
</cfquery>
<cfelse>
<cfquery name="qCreate" datasource="#somedatasource#">
INSERT INTO tblKalendarCategories
( CategoryName, CategoryBGColor, CategoryTextColor )
VALUES
( '#form.CategoryName#', '#form.CategoryTextColor#')
</cfquery>
</cfif>
Solution: Encapsulate Data Access
DAO.read();
DAO.delete();
DAO.exists();
DAO.save();
DAO.create();
DAO.update();
Bad or No Indexing
Cacheability
Caching Layers
Caching HTTP Responses
Request:
GET /index.html HTTP/1.1
Host: www.example.com
Response:
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-
Hat/Linux)
Last-Modified: Wed, 08 Jan 2003
23:11:55 GMT
ETag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 131
Accept-Ranges: bytes
Connection: close
Caching HTTP Responses
Designing for a CDN or Reverse
Proxy Cache
● Use HTTP verb “GET” for cacheable content
● Use Last-Modified and Etag headers properly
● Encapsulate code that changes content to
centralize cache purge activity
● Personalize with Cookies/Javascript
● Set up shadow DNS to bypass caching
● Use Javascript for interactions
● Design data for high cache hit ratios
Caching Data
NoSQL as a Cache{
"_id" : ObjectId("51fff472e09a41ac19dd1876"),
"NAME" : "Dan",
"KIDS" : [
{
"NAME" : "Nick",
"AGE" : 2,
"HAIR" : "blonde"
},
{
"NAME" : "Jack",
"AGE" : 1,
"HAIR" : “none”,
}
]
}
NoSql Cache Diagram
Designing for a NoSQL Cache
● Encapsulate calls to NoSQL engine
● Encapsulate data publish methods
● Design Content Purge algorithms well
● Ensure the NoSQL engine is the authoritative
source for the data being stored
Key/Value stores
Key Value Store Cache Diagram
Designing for a Key Value Store
Cache
● Encapsulate data access calls so you can
purge/reload
● Avoid cffunction output=”true”
● Choose correct cache expiry strategy (time,
LRU)
● Easy to integrate with CF ORM
● Use to remove load hotspoting
<cfcomponent>
<cffunction name="loadProduct" returntype="Product" access="public">
<cfargument name="ProductID" type="numeric" required="true"/>
<cfset var CacheKey = makeProductCacheKey(arguments.ProductID)/>
<cfif variables.Cache.exists(CacheKey) IS false>
<cflock name="#CacheKey#" timeout="10">
<cfif variables.Cache.exists(CacheKey) IS false>
<cfset variables.Cache.put(CacheKey,
variables.ProductService.get(arguments.ProductID))/>
</cfif>
</cflock>
</cfif>
<cfreturn variables.Cache.get(CacheKey)/>
</cffunction>
<cffunction name="saveProduct" returntype="Product" access="public">
<cfargument name="ProductID" type="numeric" required="true"/>
<cfargument name="Name" type="text" required="true"/>
<cfset var CacheKey = makeProductCacheKey(arguments.ProductID)/>
<cfset var Product = variables.ProductService.get(arguments.ProductID)/>
<cfset Product.setName(arguments.Name)/>
<cfset Product = variables.ProductService.save(Product)/>
<cfset variables.Cache.set(CacheKey, Product)/>
<cfreturn variables.Cache.get(CacheKey)/>
</cffunction>
<cffunction name="makeProductCacheKey" returntype="string" access="private">
<cfargument name="ProductID" type="numeric" required="true"/>
<cfreturn "Product_#val(arguments.ProductID)#"/>
</cffunction>
</cfcomponent>
Alternate Cache Methods
Time is Money
Thanks
Dan Wilson
nodans.com
twitter.com/DanWilson
www.linkedin.com/in/profile
ofdanwilson
Appendix and helpful links
A Note for MySQL users
[mysqld]
innodb_file_per_table
1. Do a mysqldump of all databases, procedures, triggers etc
except the mysql and performance_schema databases
2. Drop all databases except the above 2 databases
3. Stop mysql
4. Delete ibdata1 and ib_log files
5. Start mysql
6. Restore from dump
A Note for MySQL users
[mysqld]
innodb_file_per_table
1. Do a mysqldump of all databases, procedures, triggers etc
except the mysql and performance_schema databases
2. Drop all databases except the above 2 databases
3. Stop mysql
4. Delete ibdata1 and ib_log files
5. Start mysql
6. Restore from dump
Content Delivery Network
PROS
● Caches HTTP Response
● Ajax Friendly
● Static Content
● TTL/Manual Purge
● Blazing Fast
● Can be geographically
distributed
● No physical infrastructure to
manage
● Pay for what you use
CONS
● Pay for what you use
● SSL is more complicated
● Testing is more complicated
● Reliant on external service
● Not a good fit for intranet
traffic
Content Delivery Options
www.akamai.com
aws.amazon.com/cloudfront
Monitoring Options
ColdFusion Server
Monitor
CFStat
New Relic – SaaS
Fusion Reactor Monitor
Nagios
Reverse Proxy Cache (Front Cache)
Reverse Proxy Cache
PROS
● Caches HTTP Response
● Ajax Friendly
● Static Content
● TTL/Manual Purge
● Blazing Fast
● Many Open Source
Products
● Low operating expense
● Can be used for intranets
CONS
● Personalization must be
client side (no session
scope)
● Content is treated as static
● Testing is more complicated
● Must Manage Physical
Infrastructure
● Often Geographically
Localized
Key Value Store
PROS
● Blazing Fast
● Can cache any in-
memory item
● Some caches are
sophisticated, some
aren't
● Can be distributed
● Simple interfaces
● Integrated in CF
CONS
● Many Cached Items
represent an HTTP
request
● What is real-time to your
application?
● Key management can
be hard
● WYCIWYG (what you
cache is what you get)
Helpful Links
In-Memory Cache
http://www.ehcache.org
http://terracotta.org/coldfusion
http://memcached.org
Reverse Proxy Cache
http://varnish-cache.org
http://www.squid-cache.org
http://trafficserver.apache.org
Tutorials on Caching
Varnish: http://bit.ly/c1puD6
Squid Video: http://bit.ly/9iZu1Z
Aaron West: http://bit.ly/a4sYcr
Rob Brooks-Bilson: http://bit.ly/txser
Terracotta Webinar: http://www.terracotta.org/webcasts
This presentation: http://tinyurl.com/cacheme
Scalability Blogs
http://cfwhisperer.com
http://highscalability.com

More Related Content

PDF
Top5 scalabilityissues
PDF
The Spring 4 Update - Josh Long
PDF
Java Web Programming [9/9] : Web Application Security
PDF
Design & Performance - Steve Souders at Fastly Altitude 2015
PDF
Managing a shared mysql farm dpc11
PDF
C fowler azure-dojo
PPTX
Nancy + rest mow2012
PDF
Bpug mcollective 20140624
Top5 scalabilityissues
The Spring 4 Update - Josh Long
Java Web Programming [9/9] : Web Application Security
Design & Performance - Steve Souders at Fastly Altitude 2015
Managing a shared mysql farm dpc11
C fowler azure-dojo
Nancy + rest mow2012
Bpug mcollective 20140624

What's hot (19)

PDF
MuleSoft ESB Payload Encrypt Decrypt using anypoint enterprise security
PDF
Advanced VCL: how to use restart
PDF
VCL template abstraction model and automated deployments to Fastly
PDF
Security and performance designs for client-server communications
PPTX
A Groovy Kind of Java (San Francisco Java User Group)
PPTX
Mojo – Simple REST Server
PPT
Java. Explicit and Implicit Wait. Testing Ajax Applications
PDF
Building Performance - ein Frontend-Build-Prozess für Java mit Maven
PDF
Apache Commons Pool and DBCP - Version 2 Update
PDF
BlockChain implementation by python
PDF
My SQL 101
PDF
Dropwizard
PDF
Pandora FMS: PostgreSQL Plugin
ODP
Remove php calls and scale your site like crazy !
PDF
Top Node.js Metrics to Watch
PDF
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
KEY
What istheservicestack
PPTX
DevOpsDays Warsaw 2015: Running High Performance And Fault Tolerant Elasticse...
PDF
20151010 my sq-landjavav2a
MuleSoft ESB Payload Encrypt Decrypt using anypoint enterprise security
Advanced VCL: how to use restart
VCL template abstraction model and automated deployments to Fastly
Security and performance designs for client-server communications
A Groovy Kind of Java (San Francisco Java User Group)
Mojo – Simple REST Server
Java. Explicit and Implicit Wait. Testing Ajax Applications
Building Performance - ein Frontend-Build-Prozess für Java mit Maven
Apache Commons Pool and DBCP - Version 2 Update
BlockChain implementation by python
My SQL 101
Dropwizard
Pandora FMS: PostgreSQL Plugin
Remove php calls and scale your site like crazy !
Top Node.js Metrics to Watch
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
What istheservicestack
DevOpsDays Warsaw 2015: Running High Performance And Fault Tolerant Elasticse...
20151010 my sq-landjavav2a
Ad

Viewers also liked (17)

PDF
Git sourcecontrolpreso
PDF
Test box bdd
PDF
API Management from the Trenches
PDF
Emberjs building-ambitious-web-applications
PDF
Refactoring your legacy app to a MVC framework
PDF
Java scriptconfusingbits
PDF
Garbage First & You
PDF
Real Time With Web Sockets
PDF
Dependency Injection
PDF
Building communities
PDF
Dependency Injection Why is it awesome and Why should I care?
PPTX
Single page apps_with_cf_and_angular[1]
PDF
Automate all the things
PDF
Fr sponsor talk may 2015
PDF
Web hackingtools 2015
PDF
Language enhancements in cold fusion 11
PDF
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Git sourcecontrolpreso
Test box bdd
API Management from the Trenches
Emberjs building-ambitious-web-applications
Refactoring your legacy app to a MVC framework
Java scriptconfusingbits
Garbage First & You
Real Time With Web Sockets
Dependency Injection
Building communities
Dependency Injection Why is it awesome and Why should I care?
Single page apps_with_cf_and_angular[1]
Automate all the things
Fr sponsor talk may 2015
Web hackingtools 2015
Language enhancements in cold fusion 11
Advanced caching techniques with ehcache, big memory, terracotta, and coldfusion
Ad

Similar to Top5 scalabilityissues withappendix (20)

PPTX
Coldfusion with Keith Diehl
PDF
Ajax Performance Tuning and Best Practices
PDF
Web-Performance
PDF
Symfony2 - from the trenches
PPTX
Scale Your Data Tier with Windows Server AppFabric
PDF
Build powerfull and smart web applications with Symfony2
PPTX
Real World Lessons on the Pain Points of Node.js Applications
PPT
Language enhancement in ColdFusion 8
PPT
Apache web server installation/configuration, Virtual Hosting
PPTX
Solving anything in VCL
PDF
Four Times Microservices - REST, Kubernetes, UI Integration, Async
PDF
Web Components With Rails
PDF
Drupal 8 Cache: Under the hood
ODP
Clug 2011 March web server optimisation
PPTX
Presentation of OrientDB v2.2 - Webinar
PDF
Performance Optimization and JavaScript Best Practices
PDF
Rich Portlet Development in uPortal
PDF
Staying Sane with Drupal NEPHP
PDF
Into The Box 2018 Ortus Keynote
PPTX
Cookies
Coldfusion with Keith Diehl
Ajax Performance Tuning and Best Practices
Web-Performance
Symfony2 - from the trenches
Scale Your Data Tier with Windows Server AppFabric
Build powerfull and smart web applications with Symfony2
Real World Lessons on the Pain Points of Node.js Applications
Language enhancement in ColdFusion 8
Apache web server installation/configuration, Virtual Hosting
Solving anything in VCL
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Web Components With Rails
Drupal 8 Cache: Under the hood
Clug 2011 March web server optimisation
Presentation of OrientDB v2.2 - Webinar
Performance Optimization and JavaScript Best Practices
Rich Portlet Development in uPortal
Staying Sane with Drupal NEPHP
Into The Box 2018 Ortus Keynote
Cookies

More from ColdFusionConference (20)

PDF
Api manager preconference
PDF
PDF
Building better SQL Server Databases
PDF
API Economy, Realizing the Business Value of APIs
PDF
Don't just pdf, Smart PDF
PDF
Crafting ColdFusion Applications like an Architect
PDF
Security And Access Control For APIS using CF API Manager
PDF
Monetizing Business Models: ColdFusion and APIS
PDF
Become a Security Rockstar with ColdFusion 2016
PDF
ColdFusion in Transit action
PDF
Developer Insights for Application Upgrade to ColdFusion 2016
PDF
Where is cold fusion headed
PDF
ColdFusion Keynote: Building the Agile Web Since 1995
PDF
Instant ColdFusion with Vagrant
PPT
Restful services with ColdFusion
PDF
Super Fast Application development with Mura CMS
PDF
Build your own secure and real-time dashboard for mobile and web
PDF
Why Everyone else writes bad code
PDF
Securing applications
PDF
Testing automaton
Api manager preconference
Building better SQL Server Databases
API Economy, Realizing the Business Value of APIs
Don't just pdf, Smart PDF
Crafting ColdFusion Applications like an Architect
Security And Access Control For APIS using CF API Manager
Monetizing Business Models: ColdFusion and APIS
Become a Security Rockstar with ColdFusion 2016
ColdFusion in Transit action
Developer Insights for Application Upgrade to ColdFusion 2016
Where is cold fusion headed
ColdFusion Keynote: Building the Agile Web Since 1995
Instant ColdFusion with Vagrant
Restful services with ColdFusion
Super Fast Application development with Mura CMS
Build your own secure and real-time dashboard for mobile and web
Why Everyone else writes bad code
Securing applications
Testing automaton

Recently uploaded (20)

PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
AI in Product Development-omnex systems
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
medical staffing services at VALiNTRY
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
ai tools demonstartion for schools and inter college
PDF
Nekopoi APK 2025 free lastest update
PDF
System and Network Administration Chapter 2
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
history of c programming in notes for students .pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Understanding Forklifts - TECH EHS Solution
Operating system designcfffgfgggggggvggggggggg
CHAPTER 2 - PM Management and IT Context
AI in Product Development-omnex systems
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
ISO 45001 Occupational Health and Safety Management System
medical staffing services at VALiNTRY
ManageIQ - Sprint 268 Review - Slide Deck
ai tools demonstartion for schools and inter college
Nekopoi APK 2025 free lastest update
System and Network Administration Chapter 2
Navsoft: AI-Powered Business Solutions & Custom Software Development
Design an Analysis of Algorithms II-SECS-1021-03
Which alternative to Crystal Reports is best for small or large businesses.pdf
history of c programming in notes for students .pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Transform Your Business with a Software ERP System
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx

Top5 scalabilityissues withappendix

  • 1. The Top 5 Things You are doing today to hinder scalability Dan Wilson
  • 2. Who is Dan Wilson  Runs ChallengeWave.com, Datacurl LLC and NCDevCon  Technical Owner of Scholastic.com, Lead Architect of Forum Group  Owner of Model-Glue  Dad of 2, Husband to 1  Loves all things technical and a good debate
  • 3. Our Top 5 List 1.Monolithic Design 2.Mis-identification/Misuse of shared resources 3.Over-reliance on Shared Scopes 4.Stupid Developer Tricks 5.Failure to design for cacheability
  • 11. Cost of WebServer File Web Server Thread + Network to File System + Disk Wait Time + Disk Seek Time + Transfer time to Webserver + Transfer time to complete HTTP Request ______________________ Total Time
  • 12. Cost of 1 ColdFusion File Web Server Cost + Network Cost to CF Server + CF Parsing or Classloading Time + Thread Wait time + Thread CPU time + Transfer time for CF buffer to Webserver ______________________ Total Time
  • 13. Cost of ColdFusion File With Query Web Server Cost + ColdFusion File Cost + Number of Queries ( Network time to DB + Query Execution Plan + Query Execution + Disk Wait + Disk Seek ) + Network time to transport result set to CF + CF Parsing Time ______________________ Total Time
  • 14. Types of Shared Resources ● Memory, CPU, Disk Space ● Disk Transfer (Databases!!) ● JVM Space ● ColdFusion template cache ● ColdFusion Threads ● Network Traffic ● Database
  • 16. Over-reliance on Shared Scopes ● Session Scope use is the largest culprit ● Sometimes you have to deoptimize a few operations in order to provide a scalable solution (like stop caching a state query in application) ● If you want to use a shared scope and want to keep an eye on scalability later, use a lookup factory.
  • 17. <cfcomponent> <cfset variables.instance = structNew() /> <cffunction name="init" returntype="CurrentUserLoader" output="false" access="public"> <cfargument name="Transfer" type="any" required="true"/> <cfset variables.transfer = arguments.transfer /> <cfreturn this /> </cffunction> <cffunction name="destroy" output="false" access="public" returntype="void" > <cfset cookie.userID = "" /> <cfset structDelete( cookie, "userID") /> </cffunction> <cffunction name="load" output="false" access="public" returntype="any" hint=""> <cfset var loggedInUserID = 0 /> <cfif structkeyExists(cookie, "userID")> <cfset loggedInUserID = cookie.userID /> </cfif> <cfreturn variables.transfer.get("User", val( loggedInUserID ) ) /> </cffunction> <cffunction name="set" output="false" access="public" returntype="void" hint=""> <cfargument name="user" type="any" required="true"/> <cfset cookie.UserID = arguments.User.getUserID() /> <cfset cookie.Email = arguments.User.getEmail() /> </cffunction> </cfcomponent>
  • 19. Stupid Developer Tricks ● Looped Queries ● Lazy-Man Pagination ● ScheduledTask-o-rama ● Database Abuse
  • 20. Problem: Query in Loop <cfloop query="OldLastLogins"> <cfquery name="UpdateUsers" datasource="#datasource#"> UPDATE Users SET Active = 0 WHERE UserID = #OldLastLogins.UserID# </cfquery> </cfloop>
  • 21. Solution?: SQL IN Statement <cfquery name="UpdateUsers" datasource="#datasource#"> UPDATE Users SET Active = 0 WHERE UserID IN #ValueList(OldLastLogins, UserID)# </cfquery>
  • 23. Solution: Joins <cfquery name="UpdateUsers" datasource="#datasource#"> UPDATE users INNER JOIN lastlogin ON users.userID = lastlogin.userID SET Active = 0 WHERE lastlogin < now() </cfquery>
  • 24. Solution: Joins <cfquery name="UpdateUsers" datasource="#datasource#"> UPDATE users INNER JOIN lastlogin ON users.userID = lastlogin.userID SET users.lastLoginDate = lastlogin.createdDate WHERE lastlogin < now() </cfquery>
  • 26. Example: Get Poll Answers <cfset PollAnswers = entityLoad("PollAnswers", { PollID=entPoll[1].getPollID() }, "")> <cfif (isArray(Poll) AND arrayLen(Poll) GT 0) AND (isArray(PollOpt) AND arrayLen(PollOpt) GT 0) AND (isArray(PollAnswers) AND arrayLen(PollAnswers) GT 0)>
  • 27. Poll Net Result JDBC Recordcount: 87,923 Query Time: 14,290 ms All that for an ArrayLen() GT 0!
  • 28. Solution: Query <cfquery name="LoadGenderUsers" datasource="#datasource#"> SELECT UserID, UserName, Email, GenderID FROM Users WHERE GenderID = '#arguments.GenderID#' </cfquery>
  • 29. Problem: Lazy Man Pagination <cfoutput query="GetParks" startrow="#StartRow#" maxrows="#MaxRows#"> #ParkName# </cfoutput>
  • 30. Solution: SQL MySql, PostgreSQL: LIMIT, OFFSET SQL Server: TOP, ORDER BY ORACLE: WHERE rownum <= 10
  • 31. Problem: No Encapsulation <cfif qExists.idexists> <cfquery name="qUpdate" datasource="#somedatasource#"> UPDATE tblKalendarCategories SET CategoryName = '#form.CategoryName#', CategoryTextColor = '#form.CategoryTextColor#' WHERE CategoryID = #form.CategoryID#' /> </cfquery> <cfelse> <cfquery name="qCreate" datasource="#somedatasource#"> INSERT INTO tblKalendarCategories ( CategoryName, CategoryBGColor, CategoryTextColor ) VALUES ( '#form.CategoryName#', '#form.CategoryTextColor#') </cfquery> </cfif>
  • 32. Solution: Encapsulate Data Access DAO.read(); DAO.delete(); DAO.exists(); DAO.save(); DAO.create(); DAO.update();
  • 33. Bad or No Indexing
  • 36. Caching HTTP Responses Request: GET /index.html HTTP/1.1 Host: www.example.com Response: HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red- Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT ETag: "3f80f-1b6-3e1cb03b" Content-Type: text/html; charset=UTF-8 Content-Length: 131 Accept-Ranges: bytes Connection: close
  • 38. Designing for a CDN or Reverse Proxy Cache ● Use HTTP verb “GET” for cacheable content ● Use Last-Modified and Etag headers properly ● Encapsulate code that changes content to centralize cache purge activity ● Personalize with Cookies/Javascript ● Set up shadow DNS to bypass caching ● Use Javascript for interactions ● Design data for high cache hit ratios
  • 40. NoSQL as a Cache{ "_id" : ObjectId("51fff472e09a41ac19dd1876"), "NAME" : "Dan", "KIDS" : [ { "NAME" : "Nick", "AGE" : 2, "HAIR" : "blonde" }, { "NAME" : "Jack", "AGE" : 1, "HAIR" : “none”, } ] }
  • 42. Designing for a NoSQL Cache ● Encapsulate calls to NoSQL engine ● Encapsulate data publish methods ● Design Content Purge algorithms well ● Ensure the NoSQL engine is the authoritative source for the data being stored
  • 44. Key Value Store Cache Diagram
  • 45. Designing for a Key Value Store Cache ● Encapsulate data access calls so you can purge/reload ● Avoid cffunction output=”true” ● Choose correct cache expiry strategy (time, LRU) ● Easy to integrate with CF ORM ● Use to remove load hotspoting
  • 46. <cfcomponent> <cffunction name="loadProduct" returntype="Product" access="public"> <cfargument name="ProductID" type="numeric" required="true"/> <cfset var CacheKey = makeProductCacheKey(arguments.ProductID)/> <cfif variables.Cache.exists(CacheKey) IS false> <cflock name="#CacheKey#" timeout="10"> <cfif variables.Cache.exists(CacheKey) IS false> <cfset variables.Cache.put(CacheKey, variables.ProductService.get(arguments.ProductID))/> </cfif> </cflock> </cfif> <cfreturn variables.Cache.get(CacheKey)/> </cffunction> <cffunction name="saveProduct" returntype="Product" access="public"> <cfargument name="ProductID" type="numeric" required="true"/> <cfargument name="Name" type="text" required="true"/> <cfset var CacheKey = makeProductCacheKey(arguments.ProductID)/> <cfset var Product = variables.ProductService.get(arguments.ProductID)/> <cfset Product.setName(arguments.Name)/> <cfset Product = variables.ProductService.save(Product)/> <cfset variables.Cache.set(CacheKey, Product)/> <cfreturn variables.Cache.get(CacheKey)/> </cffunction> <cffunction name="makeProductCacheKey" returntype="string" access="private"> <cfargument name="ProductID" type="numeric" required="true"/> <cfreturn "Product_#val(arguments.ProductID)#"/> </cffunction> </cfcomponent>
  • 51. A Note for MySQL users [mysqld] innodb_file_per_table 1. Do a mysqldump of all databases, procedures, triggers etc except the mysql and performance_schema databases 2. Drop all databases except the above 2 databases 3. Stop mysql 4. Delete ibdata1 and ib_log files 5. Start mysql 6. Restore from dump
  • 52. A Note for MySQL users [mysqld] innodb_file_per_table 1. Do a mysqldump of all databases, procedures, triggers etc except the mysql and performance_schema databases 2. Drop all databases except the above 2 databases 3. Stop mysql 4. Delete ibdata1 and ib_log files 5. Start mysql 6. Restore from dump
  • 53. Content Delivery Network PROS ● Caches HTTP Response ● Ajax Friendly ● Static Content ● TTL/Manual Purge ● Blazing Fast ● Can be geographically distributed ● No physical infrastructure to manage ● Pay for what you use CONS ● Pay for what you use ● SSL is more complicated ● Testing is more complicated ● Reliant on external service ● Not a good fit for intranet traffic
  • 55. Monitoring Options ColdFusion Server Monitor CFStat New Relic – SaaS Fusion Reactor Monitor Nagios
  • 56. Reverse Proxy Cache (Front Cache)
  • 57. Reverse Proxy Cache PROS ● Caches HTTP Response ● Ajax Friendly ● Static Content ● TTL/Manual Purge ● Blazing Fast ● Many Open Source Products ● Low operating expense ● Can be used for intranets CONS ● Personalization must be client side (no session scope) ● Content is treated as static ● Testing is more complicated ● Must Manage Physical Infrastructure ● Often Geographically Localized
  • 58. Key Value Store PROS ● Blazing Fast ● Can cache any in- memory item ● Some caches are sophisticated, some aren't ● Can be distributed ● Simple interfaces ● Integrated in CF CONS ● Many Cached Items represent an HTTP request ● What is real-time to your application? ● Key management can be hard ● WYCIWYG (what you cache is what you get)
  • 59. Helpful Links In-Memory Cache http://www.ehcache.org http://terracotta.org/coldfusion http://memcached.org Reverse Proxy Cache http://varnish-cache.org http://www.squid-cache.org http://trafficserver.apache.org Tutorials on Caching Varnish: http://bit.ly/c1puD6 Squid Video: http://bit.ly/9iZu1Z Aaron West: http://bit.ly/a4sYcr Rob Brooks-Bilson: http://bit.ly/txser Terracotta Webinar: http://www.terracotta.org/webcasts This presentation: http://tinyurl.com/cacheme Scalability Blogs http://cfwhisperer.com http://highscalability.com