Making the web faster

June 26th, 2009

It was about time!

Google has announced an initiative to help developers to make their applications and websites to run faster. Nothing better than Google to push this kind of movement.

Let’s make the web faster is the main page, filled with increasing number of articles and videos on page speed optimization. Check it out!

I’m looking for ways to setup an automated script that will run YSLOW and PageSpeed tests on any given site. The idea is to monitor a site’s performance over time. You work hard to reach something around 90/95 on these test reports, and you don’t want other developers in the team (or yourself) to mess things up one month ahead, when you completely forgot about page’s performance :) So, if you know something about this, please let me know. Thanks!

Melhorando a performance de um site no browser

June 26th, 2009

Postei um artigo no blog de Tecnologia da Locaweb. Confira abaixo o artigo na íntegra.

Melhorando a performance de um site no browser” (client-side).

Escalar um site para atender milhões de usuários é sempre bom. Mas isto raramente é o problema. O mais importante é melhorar o tempo de carregamento ou renderização de uma página no browser. Aqui os segundos fazem diferença entre um site que abre “num estalo” e outro que demora a carregar acabando por frustrar o visitante.

Para melhorar a performance client-side de seu site existem diversos itens que você precisa aperfeiçoar em seu site:

- Reduzir o número de componentes na página. Uma página com 30 imagens, 10 arquivos CSS e 15 arquivos Javascript realmente vai demorar um certo tempo para ser carregada no browser. É possível reduzir isto tudo para, digamos, 2 imagens, 1 arquivo CSS e 1 arquivo Javascript, usando CSS Sprites e técnicas de consolidação de arquivos. Agora sim seu site carregará muito mais rápido;

- Usar técnicas de cache client-side. Arquivos que não mudam tão frequentemente como o logotipo de seu site, alguns ícones, e até arquivos CSS e Javascript podem usar o cabeçalho HTTP “Expires” fazendo com que browsers mantenham estes arquivos em cache local, afinal pra que baixar os mesmos arquivos toda vez que um visitante abre seu site? Para isto funcionar direito, você precisará expirar os arquivos atualizados com um número sequencial, por exemplo: logotipo.jpg?20090622001 (ano/mês/dia/alteração_do_dia).

Estes não são os itens mais importantes e nem os únicos. Para ver uma lista completa de coisas que influenciam na velocidade de seu site, baixe o plugin YSlow no Firefox, e rode o teste de velocidade em seu site. Quanto maior a nota, mais rápido é seu site. No relatório existem explicações sobre o motivo daquele item impactar na velocidade de seu site, e o mais importante: como fazer para melhorar.

Um plugin semelhante e bem recente é o Page Speed da Google. Um ponto forte dele é conter diversas ferramentas que ajudam na otimização de seu site, dentre elas, uma excelente que gera online uma versão otimizada das imagens, permitindo que você possa usá-las no site imediatamente. Por exemplo: se uma imagem banner.jpg contém 100KB, você pode gerar uma versão otimizada com apenas 30KB (depende de imagem para imagem), economizando em transferência de dados e velocidade de carregamento.

Um blog interessante que fala sobre este tópico, é o blog de Steve Souders, autor do livro High Performance Web Sites. Tanto o blog como o livro são extremamente recomendados.

Hidden Costs of Scaling Up vs. Scaling Out

June 25th, 2009

The well-known dilemma: scale vertically (buy hardware) or scale horizontally (add machines)?

Here’s an interesting point of view from an article at Coding Horror entitled

It’s fair to conclude that scaling out is only frictionless when you use open source software. Otherwise, you’re in a bit of a conundrum: scaling up means paying less for licenses and a lot more for hardware, while scaling out means paying less for the hardware, and a whole lot more for licenses.

All in all I still prefer scaling out, so you don’t have a single point of failure.

Flickr engineers do it offline

June 15th, 2009

parking_lot

Here’s a very interesting post on how Flickr engineers handle the scaling challenges of this well-known photo website: using queues to run slow things offline.

Here’s an excerpt:

“It seems that using queuing systems in web apps is the new hottness . While the basic idea itself certainly isn’t new, its application to modern, large, scalable sites seems to be. At the very least, it’s something that deserves talking about — so here’s how Flickr does it, to the tune of 11 million tasks a day.”

Check the full article out.

Boo Box web servers layout and application scaling tips

May 30th, 2009

infra-boo-box2

Boo Box, the ad network, released a layout of their web servers’ infrastructure. It seems the beast is growing fast and this diagram shows how they’re coping with the challenge.

Here are some things I found very interesting:

  • Separate servers for reading and writing (MySQL). This way you can optimize servers for a specific purpose (read or write), since the reads and writes aren’t competing with each other anymore in the disk or memory;
  • Serve static files from a different domain to speed things up is well-known, but serving them right from the RAM is new to me. However some people disagree with caching files in memory, beyond what the OS already does in this field. The other good thing is that Nginx is a super fast web server, and it’s replacing Apache in many scenarios;
  • The use of a queue server for handling time-consuming tasks is paramount for horizontal scaling. Everything that takes more than a few miliseconds (or do some sort of processing) should be ran in an asynchronous way.

It’s very nice of them to share this layout. Thanks guys!

Trânsito Não! Um experimento com Twitter, Trânsito e Ruby on Rails

April 26th, 2009

O Twitter se tornou uma grande ferramenta para interação social, já até ameaçando o conteúdo oferecido em blogs.

Indo ainda mais longe, alguns já falam que não importa mais quantos seguidores você tenha no Twitter, mas que a pessoa com maior autoridade é aquela com o maior número de mensagens “retweetadas”, mostrando então que o que esta pessoa escreve é conteúdo bom e merece ser repassado a todos.

O projeto Trânsito Não! é um experimento social com Twitter e um assunto que deixa todo mundo fora de si: o trânsito. Este website conta tweets enviados como idéias e/ou votos, gerando um espaço público de discussão sobre um dos problemas mais urgentes destes dias.

Este projeto é direcionado a todo o Brasil, só que mais especialmente aquelas pessoas que vivem na Grande São Paulo, uma região com cerca de 17 milhões de habitantes que experimentam um dos maiores volumes de tráfego de veículos do mundo.

Usei Ruby on Rails para construir este site. Este framework web oferece grande produtividade ao desenvolvedor. Se você ainda não assistiu, não deixe de ver este vídeo que mostra a criação de um blog em apenas 15 minutos usando Ruby on Rails.

O sistema de votação funciona assim: você envia um tweet (no Twitter) com uma idéia ou solução para resolver o problema do trânsito. Esta idéia vira então uma “idéia” dentro do Trânsito Não! Cada retweet da sua idéia, vira um voto. Então quanto mais a sua idéia se espalhar no Twitter, mais votos ela recebe no site. Os tweets são obtidos do Twitter através de uma API que é lida a cada minuto. As idéias ou votos são adicionados ao banco de dados, e as páginas são geradas novamente.

Você pode me encontrar em meu blog, Twitter, ou por e-mail.

Transito Não! An experiment with Twitter, Traffic Jams and Ruby on Rails

April 26th, 2009

Twitter has become a great tool for social interaction, and it’s also gaining more authority than content in blogs.

Going even further, some people say it doesn’t matter how many followers you have on Twitter, but instead what matters is how many times your tweets get forwarded by those following you, showing that this person writes more valuable content, which deserves to be sent over to other people.

The project Trânsito Não! (which stands for “No To Traffic!”) is a social experiment with Twitter and a subject that gets everyone mad: the traffic jams. This web app cast tweets as ideas and/or votes, generating a public web space to debate on one of the most urgent problems of these days.

This project is aimed at the Brazilian people, specially those people living in the greater area of Sao Paulo, a region with about 17 million people experiencing one of the biggest car traffics in the world.

I developed this website with Ruby on Rails. This web framework offers great productivity to the developer. If you haven’t the chance yet, don’t miss this video showing a complete web blog written in only 15 minutes using Ruby on Rails.

The voting works like this: you tweet some idea or solution for the traffic problems, followed by the hashtag #transitonao. This tweet becomes a “idea” on TransitoNao website. If your tweet gets retweeded X times, these X times become votes for your idea. So the longer your idea spreads, the more votes you get. New tweets are read from the Twitter API every minute, being added to the database, and the pages being also refreshed (using page caching).

You can find me on my blog, Twitter, or at my personal email.

What is SCRUM? Learn it in less than 10 minutes

February 12th, 2009

This guy put together a presentation on what is SCRUM. It’s very informative and to the point. “By the end of this fast-paced video, you’ll know about burn-down charts, team roles, product backlogs, sprints, daily scrums and more.”

I’m so glad I’m able to breathe, because this guy wasn’t :)

Testing route helper methods and formatted routes

February 7th, 2009

Here’s a quick tip on how to test those helpers such as ‘new_post_path’ and ‘home_path’. Also those formatted routes such as ‘formatted_posts_path’. And why is important to test those.

Here’s how I test route helper methods.


# spec/controllers/ideas_controller_spec.rb

describe IdeasController do
  describe "GET /ideas/new" do
    it "should have helper method new_idea_path" do
      get :new
      new_idea_path.should_not be_nil
      new_idea_path.should == '/ideas/new'
    end

    it "should have helper method formatted_new_idea_path" do
      get :new, :format => :json
      formatted_new_idea_path.should_not be_nil
      formatted_new_idea_path.should == '/ideas/new.json'
    end

    (...)
  end
end

And why it’s important to test those methods, since they’re already tested by Rails tests?

Rails 2.3 has removed all those formatted_xxx named routes. Turns out these routes ate up a lot of memory and served minimal purpose. Read article here.

So if you use something like formatted_new_user, and you need to upgrade the application to Rails 2.3, it would be broken without test coverage.

Cucumber generic method for handling Webrat visit method

February 7th, 2009

Here’s a tip for creating a generic Cucumber step, handling the Webrat visit method.

Imagine you have many Cucumber scenarios, and you have many steps like these:


  Given I am on the new task page
  Given I am on the new project page
  Given I am on the home page

This way you’d have to create mapping between these strings above, to real paths inside the application. You could use the method ‘path_to’, which is already provided with Cucumber, inside features/support/paths.rb. That could lead to something like this:


# features/support/paths.rb

def path_to(page_name)
  case page_name

  when /new task/i
    new_task_path
  when /tasks/i
    tasks_path

  when /new user/i
    new_user_path
  when /users/i
    users_path

  when /home/i
    root_path

  # and so forth...

  else
    raise "Can't find mapping from \"#{page_name}\" to a path."
  end
end

Or you could use something more generic and more maintanable.

So, let’s take advantage of the path helpers already provided by Rails such as new_task_page, tasks_path, home_path, and do this instead:


  Given I am on the new_task page
  Given I am on the new_project page
  Given I am on the home page

And add this to your create_task_steps.rb:


# features/step_definitions/create_task_steps.rb

Given /^I am on the (.+) page$/ do |page_name|
  eval("visit #{page_name}_path")
end

This way Webrat will visit the path: new_page_path, and you won’t have to maintain the paths.rb file.