Wednesday, February 2, 2011

Persisting Tuning

Persisting tuning has been drilled into my head early in my career and I understand the term, "earlier is cheaper". At the beginning of my career I worked for a major bank on a data warehouse. I worked as a junior developer along side with some pretty solid data architects. I learned a lot about databases. Specially, that they are notorious for bottlenecks in applications. Later in my career, I worked on web development projects. I found love with the Spring framework and ORM (Hibernate and Ibatis). Here are my thought regarding a presentation done by Thomas Risberg, a senior consultant from SpringSource, he stated the following:
There is no silver bullet when it comes to persistence tuning. You have to keep an open mind an approach the problem systematically from a variety of angels
The presentation did not touch on "big data" and the NoSQL movement. However, there is still a lot of good stuff in it, specially if you are using Java, Spring, Hibernate, and an ODBC.

Currently, I have been working on an application that needed to support up to 200 messages per second. Below are a few strategies and process that I implemented to try to increase three major task:
  1. Performance: response time needs to be in millisecond
  2. Scalability: able to hold 200 message per second
  3. Availability: able to scale horizontally (not buying a bigger box, but getting a similar box)
DBA - Developer Relationship
When creating a database, you have two tasks as a DBA:
Operational DBA:
  • ongoing monitoring and maintenance of database system
  • keep the data safe and available
Development DBA:
  • plan and design new application database usage
  • tune queries
The Operational DBA role is the following:
  • Data volumes, row sizes
  • Growth estimates, update frequencies
  • Availability requirements
  • Testing/QA requirements
Development DBA role is the following:
  • Table design
  • Query tuning
  • Maintenance policies for purging/archiving

Database Design:

Database design can play a critical role in application performance

Guidelines:
  • Pick appropriate data types
  • Limit number of columns per table
  • Split large, infrequently used columns into a separate one-to-one table
  • Choose your index carefully - expensive to maintain. improves query
  • Normalize your data
  • Partition your data

Application Tuning

Balance performance and scalability concerns. For example, full table-lock could improve performance but hurt scalability

Improve concurrency
  • Keep your transactions short
  • Do bulk processing off-hours
Understand your database system's locking strategy
  • some lock only on writes
  • some locks on reads
  • some escalate row locks on table locks

Performance improvements
Limit the amount of data you pull into the application layer
  • Limit the number of rows
  • Select only the column you need

Tune your ORM and SQL

  • consider search criteria carefully
  • avoid NULLS in the where clause - NULLS aren't index
  • avoid LIKE beginning with % since index might not be used

Spring Data Access Configuration:

Pick a transaction management that fits your application needs
  • Favor a local resource DataSourceTransactionManager
  • Using a container managed DataSource can help during Application Server support calls
  • JtaTransactionManager using XA transactions is more expensive. Warning: XA transaction sometimes needed whenJMS and database access used together
Why XA are more expensive? Because of its setup and its overhead
Setup includes:
  • run a transaction coordinator
  • XA JDBC driver
  • XA Message Broker
  • put the XA recovery log to a reliable log storage
XA has a significant run time overhead
  • two phase commit
  • state tracking
  • recovery
  • on restart: complete pending commits/rollbacks --> read the "reliable recovery log"

General transaction points:
  • Keep your transactions short to avoid contention
  • Always specify the read-only flag where appropriate, in particular for ORM transactions
  • Avoid SERIALIZABLE unless you absolutely need it

JDBC Tuning
Connection to the database is slow - use a third-party connection pool like DBCP, C3PO or native one like oracle.jdbc.pool.OracleDataSource. Never use DriverManagerDataSource

Improve availability by Configuration the DataSource to survive a database restart. Specify a strategy to test that connectionare alive
  • JDBC 4.0 isValid()
  • simple query
  • metadata lookup
Consider a clustered high-availability solution like Oracle RAC


Use Prepared Statements
  • Use prepared statements with placeholder for parameters - like select id, name from customers where age > ? and state = ?
  • Prepared statements allow the database to reuse access plans
  • Prepared statements can be cached and reused by the connection pool to improve performance
  • The JdbcTemplate can be configured using setFetchSize
  • Larger fetchSize let you lower the number of network roundtrips necessary when retrieving large results
Favor query() methods with custom RowMapper vs. queryForList().
queryForList() uses a ColumnMapRowMapper which generates a lot of expensive HashMaps

private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public List> getList() {
return this.jdbcTemplate.queryForList("select * from mytable");

Using column index instead of column label does give a slight speed advantage but it makes code harder to read and maintain

public Actor findActor(String specialty, int age) {

String sql = "select id, first_name, last_name from T_ACTOR" +
" where specialty = ? and age = ?";

RowMapper mapper = new RowMapper() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setId(rs.getLong("id"));
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
};


// notice the wrapping up of the argumenta in an array
return (Actor) jdbcTemplate.queryForObject(sql, new


ORM Tuning
  • Don't load more data than needed - use lazy loading
  • Can however result in many roundtrips to database - n+1 problem
  • Avoid excessive number of database roundtrips by selective use of eager loading
  • Consider caching frequently used data that's rarely updated
  • Learn specific fetching and caching options for your ORM product
Determine a good fetch strategy (Hibernate)
  • use "select" fetch mode for relationships needed sometimes - result in 1 or 2 queries
  • use "join" fetch mode for relationships needed all the time 0 limit to single collection for one entity since the results for multiple joins could be huge
  • Fetch mode can be specified statically in the ORM mapping or dynamically for each query
  • Capture generated SQL to determine if your strategy generates expected queries
  • Use to prefetch a number of proxies and/or collections
  • Caching allows you to avoid database access for already loaded entities

Enable shared (second-level) cache for entities that are read-only or are modified infrequently
  • Include data when not critical it's kept up-to-date
  • Data that's not shared with applications
  • Choose an appropriate cache policy including expiration policy and concurrency strategy (read-write, read-only ...)

Consider enabling query cache for query that is repeated frequently and where the referenced table aren't updated very often

More on Hibernate: "Working with Hibernate with Spring 2.5" with Rossen Stoyanchev


Bulk Operations
  • Perform bulk operations in database layer if possible
  • SQL statements - update, delete
  • Stored procedures
  • Native data load tools
  • From the application layer - use batch operations
  • JdbcTemplate - batchUpdate
  • SimpleJdbcInsert - executeBatch
  • SpringBatch - BatchSqlUpdateItemWriter
  • Hibernate - set hibernate jdbc.batch_size and flush and clear session after each batch

SQL Tuning
SQL is the biggest bottleneck when it comes to performance problems
  • Capture the problem SQL
  • Run EXPLAIN
  • Make adjustments
  • ANALYZE
  • Tweak optimizer
  • Add index
  • Repeat until adequate performance

Capture SQL Statements
  • Use JPA - add to LocalContainerEntityManagerFactoryBean
  • Using Hibernate - add to LocalSessionFactoryBean
  • Alternative using Hibernate with Log4J

Database Specific Tools:
- MySQL has a Slow Query Log

---log-slow-queries and --log-queries-not-using-index
Analyze Tables and Indexes
  • Use ANALYZE to provide statistics for the optimizer (Oracle)
  • Other database use similar commands
  • Learn how the optimizer works for specific database
Summary
  • Capture your SQL and run Explain/Autotrace on the slowest statements
  • Review your DataSource and Transaction configurations
  • Work with your DBAs to tune applications and database

Back at it!

I have not been able to update my blog. Towards the end of last year, my daughter, Juliana Olivas, was born. Therefore, I'm now trying to change the world one diaper at a time. Also, I'm trying to stay awake and keeping up with my current job at Up-Mobile. I am hoping to start updating my blog this week.

Thursday, August 26, 2010

Run all your Groovy test cases using Ant

I needed to run all my Groovy unit test cases using Junit ant task, but for whatever reason I was not able to do it. I was able to do it using the following:

Wednesday, August 25, 2010

XML and Unit testing

I had to verify some XML using simple a String to verify. The code is the following:

public class FetchMessageServiceTest {
...
private static final String XML_INCOMING = "secretpassword876512345098765432155225testing 1,2";

@Test
public void shouldReturnAnXml() throws SAXException, IOException {
FetchMessageService service = new FetchMessageService(jmsTemplate, incomingService);
assertNotNull(service);
Redirection redirectionMock = getRedirection();
String xml = service.getXml(redirectionMock);
assertNotNull(xml);
assertEquals(XML_INCOMING, xml);
}


When I ran the Junit task in Eclipse, everything was fine. But when I ran it in Junit Ant task, I got the following error:

[junit] expected:<<?xml version=["1.0" encoding="UTF-8"]?>    [junit] <redirection><aut...> but was:<<?xml version=['1.0' encoding='UTF-8']?>
[junit] <redirection><aut...>
[junit] <redirection><aut...> but was:<<?xml version=['1.0' encoding='UTF-8']?>
[junit] <redirection><aut...>


I then decided to use XMLUnit. Once I end up doing this, everything worked perfect. I am not sure if it is something with the output of the Ant or if it's something with String. The code is the following:

@Test
public void shouldReturnAnXml() throws SAXException, IOException {
FetchMessageService service = new FetchMessageService(jmsTemplate, incomingService);
assertNotNull(service);
Redirection redirectionMock = getRedirection();
String xml = service.getXml(redirectionMock);
assertNotNull(xml);
XMLAssert.assertXMLEqual(XML_INCOMING, xml);
}


Everything seems to be working fine. I'm not sure if the problem with the test was with the output of Ant. I believe that it might be something to do with the output of the console and the encoding that it uses, but either way XMLUnit seems to be a great candidate for testing any type of XML regardless of the format.

Monday, August 23, 2010

Marshalling XML- Castor vs. Groovy MarkupBuilder

I worked on a small project where I needed to use some type of XML marshalling. I end up using Spring's (version 3) integration with Castor and JMS (ActiveMQ). I find it not that much flexible and eventually ended up using Groovy's XML libraries (really nice).

We had problems using the "conversion" of JMS (from object to JMS message), we find it easier to use an XML to transfer the messages in the JMS queue. The object that I wanted to convert to XML was a value object (immutable no setters) and using static factory. The object is the following:

public final class Redirection {

private RegisteredDate registeredDate;
private Authentication authentication;
private OperatorAndService operatorService;
private TextMessage textMessage;

private Redirection() {}


private Redirection(Authentication authentication,
OperatorAndService operatorService, TextMessage textMessage, Date date) {
this.authentication = authentication;
this.operatorService = operatorService;
this.textMessage = textMessage;
registeredDate = RegisteredDate.get( date!=null?date:new Date());
}

...

public static Redirection get(Authentication authentication,
OperatorAndService operatorService, TextMessage textMessage, Date date) {
return new Redirection(authentication, operatorService, textMessage, date);
}

...

public Authentication getAuthentication() {
return authentication;
}

public OperatorAndService getOperatorAndService() {
return operatorService;
}

public TextMessage getTextMessage() {
return textMessage;
}

public RegisteredDate getRegisteredDate() {
return registeredDate;
}

@Override
public String toString() {
return "Authentication: " + authentication + ", operator service: "
+ operatorService + ", text message: " + textMessage +
", registed date: " + registeredDate;
}
}


The implementation of the Castor is pretty simple using Spring 3:








I used the mapping, since I needed to pass three objects to the static factory to create my Redirection object (Authentication, OperatorAndService, and Textmessage). The mapping file was the following:



Mapping for the redirection object
























The "get-method" is exactly what it means, is the method that you will use to fetch the object. The set-method is in case you have any setters (perfect for DTOs). However, my class is immutable so there are no setters. Instead, there is one static method that contains the three parameters that I needed to pass. There is a way to create an object without a constructor "verify-construcable=false". I wanted to see if there is a way to pass all the four object to my static factory, however, this did not work. The creation of the XML worked but not the creation of the object from the XML. I got the following error:

Castor unmarshalling exception; nested exception is org.exolab.castor.xml.MarshalException: unable to find matching public constructor for class

I try to look for a solution, but I had to tweak a lot of things to create a Redirection object. I then decided to look at Groovy's MarkupBuilder.


class XmlService {
private XmlService() {}

public static String getXml(Redirection redirect) {
if(redirect == null) {
throw new IllegalArgumentException("Redirection is invalid or null")
}

Authentication credentials = redirect.getAuthentication()
OperatorAndService operAndServ = redirect.getOperatorAndService()
TextMessage sms = redirect.getTextMessage()

def xml = new groovy.xml.StreamingMarkupBuilder()
xml.encoding = "UTF-8"
def redirection = {
mkp.xmlDeclaration()
redirection() {
authentication() {
username(credentials.getUsername())
password(credentials.getPassword())
}
operatorAndservice() {
serviceId(operAndServ.getServiceId())
operatorId(operAndServ.getOperatorId())
}
textmessage(){
phone(sms.getPhone())
shortcode(sms.getShortcode())
message(sms.getMessage())
}
registerdate(date:redirect.getRegisteredDate())
}
}

return xml.bind(redirection);
}


public static Redirection toRedirection(String xml) {
if(Validation.isEmpty(xml)) {
throw new IllegalArgumentException("The application needs to have an xml")
}

def redirectionXml = new XmlParser().parseText(xml)
//Authentication
String username = redirectionXml.authentication.username.text()
String password = redirectionXml.authentication.password.text()
def authentication = Authentication.get(username, password)

//Operator and service
String serviceId = redirectionXml.operatorAndservice.serviceId.text()
String operatorId = redirectionXml.operatorAndservice.operatorId.text()
def operatorAndService = OperatorAndService.get(operatorId, serviceId)

//Text message
String phone = redirectionXml.textmessage.phone.text()
String shortcode = redirectionXml.textmessage.shortcode.text()
String message = redirectionXml.textmessage.message.text()
def textMessage = TextMessage.get(phone, shortcode, message)

String registerDate = redirectionXml.registerdate[0].'@date'
def registeredDate = RegisteredDate.get(registerDate)

return Redirection.get(authentication,
operatorAndService, textMessage,
registeredDate.getRegisteredDate());
}
}
Groovy is a better candidate for this application. Its simplicity and flexibility beats Castor. The only thing that concerned me is the performance. I did noticed that the test cases using Castor were much faster. In case that performance is an issue, consider using Castor or other type of XML marshaling. I heard from one of my coworkers that xstream is very fast.

Wednesday, July 28, 2010

Keep your pulse on your business model

A friend told me about an anecdote of a start-up that was obviously heading in the wrong path. The company was quickly loosing money and yet the market was huge. The CEO fired the head of sales and marketing and decided to manage the department. Luckily, they had one thing in their favor, a lot of data. After some analysis and data mining, they realized that the B2C business model was no sustainable. Worse, there were signs of this about a year ago (sales plummeted). They did a small market research and talked with the customers. At the end, they found out the following based on their analysis:
  1. Accounts receivables were taking a nose dive
  2. There were several disruptive technologies and the market had changed
  3. Customers were unhappy with the current business model (the payable from our customers were lower than 70%)
  4. The B2C product had become a commodity and the only way to compete was through money (lower profits)
  5. Customers were looking into a more enterprise product

At the end, the company decided that a new product was needed. A product focused on B2B. With a small pilot they were able to "test the waters" and provide a successful use case. They are now selling the product and making sure that the same mistake doesn't happen again.

I've seem this type of behavior in current businesses. I'm a believer that when you get encountered with this type of issues, departments try to tackled it by using "brute force". I don't believe that this company's sales and marketing department were oblivious of the problem. Instead, I believe that they were just sticking to their strategy. They were too caught up with the every day details of trying to maintain their quota and get more customers. But, they didn't have the pulse on the market. In other words, no one checked if the business model was working.

A few weeks ago, I sat down with a founder of a company which I respect very much. The company was founded by three individuals. He was the COO, another founder became the head of sales, and the last one was a series entrepreneur. He explained that most of their success was mostly due to the management style of the sales manager (company started about 4 years ago and it was worth above $44 million). They called it, "One Hundred Days". Senior management would come up with a goal for the entire company that needed to be executed in the next 100 days. Then, whatever decision, customer, sales had to answered the following questions:

  • Is this according to the plan?
  • Would this get us closer to the plan?
  • Lets check the plan again.

I really like the idea. However, I would add a check and balance approach. You can easily loose focus in the every day task just like the head of marketing and sales in my friend's company. It is what Eric Ries calls "the pivot point".
Pivot is the ability to change direction in response to failure. Within every failure is a good idea waiting for the right circumstance or application. Pivot is an incremental and "zig-zagging path" towards the right market fit. The faster the pivot, the more likely a startup will find success before running out of money.
Ries contends that startups must be "built to learn", meaning validated learning about what customers want has to be the unit of measurement for company success. Turning ideas into products, and testing those ideas against reality, allows the company to pivot effectively, enabling customer-centered testing to be done by the dozen, or even, by the hundred.

A few months ago, I read a blog You're in a Museum by Steve Woodruff. He explained, the fact that there is always room for improvement and we should constantly try to seek for better solutions. He proposed to start thinking in different direction by asking the following questions:
  1. What is actually not working?
  2. What is missing and should be created?
  3. How could this be better?
  4. What new connections can be made?
  5. What do I want to leave behind as a legacy?
  6. How can ideal become real?
  7. What would I REALLY want to make happen if there were no limits?
  8. Why? And, while we're at it - why not?
In other words - question the status quo. We need to know when to change course or when our strategy is no longer working.

Friday, July 23, 2010

Groovy on Grails

I've been playing with Groovy and Grails for the past month. We had a demand of a few sites that needed to be constructed. The sites were small and needed to have some basic CRUD method and a small business rules. Then, we had to tie it with our SMS Gateway that we have developed. We evaluated a few languages, but at the end we chose Groovy for the following reasons:
  1. Dynamic language
  2. It sits in the JVM
  3. Easy to develop sites
We have been playing with the following versions:
  • Grails 1.3.3
  • Groovy 1.6.0_20
I have the most respect for the team who build this programming language. The language is very easy to read and the learning curve is very small. The integration that they did with Java, Spring, and Hibernate is very nice. The ORM tool that they created, GORM is very nice and very easy and quiet frankly it's my favorite.



class User {

String userId
String password
String homepage
Date dateCreated
Profile profile
...

}

User has a one to one relation with profile.

class Profile {
static belongsTo = User

byte[] photo
String fullName
String bio
String homepage
String email
String timezone
String country
String jabberAddress

static constraints = {
fullName(nullable: true)
bio(nullable: true, maxSize: 1000)
homepage(url: true, nullable: true)
email(email: true, nullable: true)
photo(nullable: true)
country(nullable: true)
timezone(nullable: true)
jabberAddress(email: true, nullable: true)

}

String toString() {
"Profile for ${fullName} (${id})"
}
}


The belongsTo is assigned the owning class, which means the relationship is unidirectional. You can get to a Profile via a User, but there’s no link back from a Profile to a User

class Post {
String content
Date dateCreated

static constraints = {
content(blank: false)
}
static belongsTo = [user: User]

static mapping = {
profile lazy: false
sort dateCreated: "desc"
}

static hasMany = [tags: Tag]
}

You can sort automatically within the mapping closure. In this example, all queries to the Post object will return in a descending order.

We use the map style of belongsTo, where we create a bidirectional link between User and Post classes. This creates a new field on Post called user that is the bidirectional mapping back to the owning User

Another useful technique is the validation of the fields. In the constraint closure you can specify the fields that need to be validated and the validation type. For example, in this case, content cannot be blank (null or empty).

The first deployment that I made was using "grails war". The con of this approach is that I look the dynamic compilation. So, if any change to the code, you would have to create the war once again, and deploy it. You gain performance but you loose the dynamism of Groovy. If performance is not a big issue, you can use "grails run-war". According to the documentation:
This is very similar to the previous option, but Tomcat runs against the packaged WAR file rather than the development sources. Hot-reloading is disabled, so you get good performance without the hassle of having to deploy the WAR file elsewherthe application is compiled with Java native code. Therefore, every change that I have to make I have to do it in Grails and deploy it once again.

I welcome your feedback in case I'm wrong.