Restore the story background

There is an old project N years ago, received an alarm message from the server, bandwidth and CPU are over 80%. Then the site opened very slow, and then hung up, the first reaction is to be brushed!

Location problem

  1. First, I checked the statistics platform and found that the number of people online at the same time was 0, which felt very strange. It immediately occurred to me that the number of people online was not 0 because the website had been down and could not perform js statistics
  2. Query the Nginx log immediately
tail -f /data/logs/nginx/access.log  
Copy the code
  1. When querying access.log, I find several interfaces scrolling wildly at a speed that is visible to the naked eye.
  2. Analysis of the logs shows that the attacker is not trying to curl the interface, but is trying to swipe the page
  3. To locate the basic are different IP, banning IP is not the solution
  4. Optimize the brushed page, located to brush is the home page, query the website home page code, found that the home page request is abnormal, the project is relatively old, the use of PHP framework YAF + Smarty rendering, and part of the interface has done data caching, but the machine still can not stand such a crazy query. (This is a small project, standalone deployment, including: Web services +MySQL+MongoDB)
  5. Brainwave, the “home page static processing” it
  6. The core idea of static processing is described in the code comments. It is very simple, but very efficient
The core ideas are as follows:/** * select * from the cache ** ** from the cache ** ** * from the cache ** ** ** Curl curl curl curl curl curl curl curl curl curl curl curl Curl = curl = curl = curl = curl = curl = curl = curl
public function indexAction()
{
    $cacheKey = 'statichtml_staticIndex';
    $result = Service_CacheModel::get($cacheKey);
    if (empty($result)) {
        // This is a dynamic page. The data in this page is dynamically generated by the request data
        $url = "https://www.xxxxx.com.cn/index/dynamic/";
        $result = Request::curl($url);
        Service_CacheModel::set($cacheKey.$result.60*10); / / for 10 minutes
    }
    echo $result;
}
Copy the code

Home page after static processing seconds open

After static processing, the home page access speed is only 33 milliseconds, compared to about 1 second before, which is a 30-fold increase in performance

note

The fact that I can solve the problem through the above solution can only prove three points

  1. The previous home page is a waste of performance, very poor
  2. The concurrency isn’t that high, or statically processing won’t solve the problem.

The above is not the fundamental way to solve the brush attack, but it is a solution to optimize performance and improve the speed of website access