Home > TYPO3 > Jak przyspieszyć działanie TYPO3 przy pomocy nginx’a.

Jak przyspieszyć działanie TYPO3 przy pomocy nginx’a.

UWAGA. Nowa wersja i nowa podstrona dedykowana tylko evo_nginx_boost http://techblog.evo.pl/evo_nginx_boost-extension/ Teraz evo_nginx_boot może pracować bez użycia NGINX’a. Wymagane jest TYPO3 i memcache!

TYPO3 cache

Kwestia wydajności TYPO3 była omawiana wiele razy. Znalazłem wiele różnych tricków, które pozwalają przyśpieszyć czas generacji strony między innymi moduł  nc_staticfilecache czy dmc_highperformance. Najnowsza wersja TYPO3, która obecnie jest w fazie alpha radykalnie zmienia podejście do cachowania, dając nam do wyboru różne mechanizmy wsparcia jak file, memcache, database, czy apc.

Problem

Wszystkie powyższe rozwiązania z wyjątkiem nc_staticfilecache mają jedną wspólną rzecz: aby odczytać cache należy wywołać proces php i odczytać scachowane dane, sparsować, a następnie wysłać do przeglądarki.
Zróbmy prosty test z wykorzystaniem narzędzia ab. Sprawdzimy ilość zapytań na sekundę z wykorzystaniem złożonej witryny.

ab -n 100 -c 1 http://localhost/
  1.  
  2. Server Software:        Apache/2.2.6
  3. Server Hostname:        localhost
  4. Server Port:            80
  5.  
  6. Total transferred:      5064709 bytes
  7. HTML transferred:       5031914 bytes
  8. Requests per second:    1.02 [#/sec] (mean)
  9. Time per request:       976.265 [ms] (mean)
  10. Time per request:       976.265 [ms] (mean, across all concurrent requests)
  11. Transfer rate:          50.66 [Kbytes/sec] received

Ilość zapytań na sekundę 1.02!

Co się stanie jeśli nasz serwis będzie musiał obsłużyć 1000 takich zapytań na sekundę? Nawet z  najbardziej wydajnym mechanizmem cachowania, każde wywołanie parsera PHP do odczytania danych spowoduje bardzo duży load na serwerze.

Nginx

Z pomocą może nam przyjść serwer proxy NGINX. Nie jest on może nowym odkryciem, ale sprytne połączenie go z TYPO3 spowoduje wzrost wydajności ponad 200x! Opisane przeze mnie rozwiązanie obsługuje ruch użytkowników zalogowanych i niezalogowanych, uwzględnia zmianę strony po zalogowaniu oraz różne ustawienia cache w TYPO3.
Teraz do rzeczy. Oto założenia naszej instalacji:

Nginx Typo3 and Memcache

Nginx Typo3 and Memcache

Użytkownik wywołuje stronę. Nginx sprawdza jego cookie. Jeśli ustawione jest cookie o nazwie nginx_boost_noCache wtedy zapytanie jest wysyłane odrazu do Apacha a później do TYPO3 z pominięciem memcache. Dzięki temu cookie możemy łatwo kontrolować kiedy bezwzględnie należy wyłączyć cachowanie w memcache. Może to zrobić w dowolnej wtyczce w naszym systemie. Poniżej  wyciąg z konfiguracji nginx do obsługi takiego przypadku

if ($http_cookie ~* “nginx_boost_noCache=1″)
  1. {
  2. proxy_pass  http://domain;
  3. break;
  4. }

W sytuacji kiedy nginx nie znajdzie cookie nginx_boost_noCache, sprawdza czy w memcache istnieje scachowana strona. Jako klucz używa $request_uri.

# set default memcache key
  1. set $memcached_key $request_uri;
  2. # Check if local memcached server can answer this request
  3. default_type text/html;
  4. memcached_pass 192.168.168.3:11211;

Jeśli nasza strona nie znajduje się w memcache, nginx ponownie wysyła zapytanie do apacha. Apache wywołuje TYPO3, generuje stronę, następnie wtyczka evo_nginx_boost  zapisuje ją do memcache z memcache_key takim samym jak żądany url.

$memcache_key  = “domain/about-us”

Kolejne wywołanie tej strony zostanie wysłane odrazu z memcache bez potrzeby uruchamiania procesu PHP.
Nasza wtyczka w pełni uwzględnia ustawienia czasu cachowania w TYPO3 dla każdej ze stron, odcztuje też wartość cache_period. Jeśli w TYPO3 nie zostało nigdzie ustawiony czas cachowania to pobieramy wartość defaultową z konfiguracji wtyczki.

Co jeśli użytkownik się zaloguje?

Wszystko zależy od nas. Możemy w nginx i evo_nginx_boost wyłączyć zupełnie cachowanie dla zalogowanych. My jednak analizując nasze potrzeby i statystyki strony doszliśmy do wniosku, że zalogowany użytkownik często w ramach jednej sesji ogląda i wraca do tych samych stron. Zmiana musi nastąpić  kiedy użytkownik wyśle żądanie POST, np: napisze komentarz, czy artykuł w blogu. W takiej sytuacji korzystamy z hooka w clasie class.tslib_fe.php – initFEuser.

Jeśli użytkownik się zaloguje ustawiamy cookie nginx_boost_fe_user o wartosci takiej samej jak fe_typo_user.

$memcache_key = “domain/blogs/us1b27c2c23bdb600912561e08a7e4886b”

Natomiast po wysłaniu POSTa lub innej operacji, która wymaga odświeżenia widoku dodajemy do tej wartości wersje. Wtyczka evo_nginx_boost następnie zapisuje do memcache  nową wersję strony.

$memcache_key = “domain/blogs/us1b27c2c23bdb600912561e08a7e4886b_1″

Po 5min wersja strony się przedawni i nginx wyśle nowe żądanie do Apacha i Typo3. Jeśli w tym czasie inny użytkownik doda  komentarz do bloga to zobaczymy to po 5min.

Warto też ustawiać małe czasy cachowania dla stron w których dane są często zmieniane. W serwisie społecznościowym o dużym obciążeniu widok strony usuwamy z cache co 1-5min to spokojnie nam wystarczy do obsłużenia bardzo dużego ruchu.

Teraz czas na testy ab dla powyższego rozwiązania.

ab -n 100 -c 1 http://localhost/
  1.  
  2. Server Software:        nginx/0.6.35
  3. Server Hostname:        localhost
  4. Server Port:            80
  5.  
  6. Total transferred:      10103800 bytes
  7. HTML transferred:       10089200 bytes
  8. Requests per second:    400.05 [#/sec] (mean)
  9. Time per request:       2.500 [ms] (mean)
  10. Time per request:       2.500 [ms] (mean, across all concurrent requests)
  11. Transfer rate:          39468.58 [Kbytes/sec] received

Ilość zapytań na sekundę 400.05!

Opis konfiguracji evo_nginx_boost

Property: Data type: Description: Default:
enable string enable disable memcaching 1
forceTimeoutToAllPages int set default memcache expiration time (has priority over TYPO3 setting) 0
disableCacheForLoogedUsers int enable/disable memcaching for logged users 0
cleanOnClearAllCache int if set, memcache is cleared when backend user click clear cache
setPageCacheTimeout OverrideAllTypoSettings int if you enable this option, you can override all expires time from your user_int extension, fg if you have page with four extensions and each extension calls static function:

if (method_exists(’tx_evo_nginx_boost’, ’setPageCacheTimeout’)
tx_evo_nginx_boost::setPageCacheTimeout($timeout);

evo_nginx_boost set expire time to the lowest value set in all 4 plugins

1
_mainServerIP string memcache server ip
_mainServerPort string memcache server port
_mainServerPersistent int enable persistant connection 1
_mainServerTimeout string memcache server connection timeout 1
memcacheSignature int add signature to end o pages 1
memcacheSignatureText string text of signature fg “CACHED BY ME :) ”. If you set memcacheSignature = 1 time of expiration is added to the end of memcacheSignatureText 1
excludedUrls array Set in ext_localconf. This is array of urls which should be excluded from memcaching. Let say you have confirmation message after successfuly saving post in user’s blog. Page with message “your post was saved” will be memcached. You can add parameter message=1 and put this in array. Evo_nginx_boost exclude this url from memcaching. 1

Wtyczka posiada również moduł BE, w którym możemy obserwować wszystkie parametry związane z serwerem memcache. W opcji cachedump można sprawdzić jakie strony z jakim memcache key zostały zapisane:

Backend module

Backend module

Całe rozwiązanie było testowane na bardzo skomplikowanej witrynie z dużą ilością różnych rozszerzeń USER i USER_INT. Czekamy na uwagi i sugestie.

Pliki do pobrania:

Uwaga:

Wersja nginxa dostępna przez apt-get w  dystrybucji ubunt 8.04.1 posiada błąd.
Bugfix: a segmentation fault occurred in worker process, if the  “memcached_pass” and “if” directives were used in the same location.

Należy pamiętać, aby czas serwera był taki sam jeśli nginx i apache są na różnych maszynach :)

  • Share/Save/Bookmark

Bartosz Aninowski TYPO3 boost, memcache, nginx, performance, przyśpieszanie, TYPO3

  1. Paweł
    marzec 26th, 2009 at 12:02 | #1

    Witam,

    literówka -> przyspieszyć, nie przyśpieszyć

    pzdr,
    PKo

  2. kwiecień 10th, 2009 at 16:23 | #2

    Bartosz, thanks for the interesting writeup;
    I’d be interested in how the performance of your nginx-memcached setup compares
    with a setup we’re running using squid as reverse proxy and typo3s cache-headers. IMHO the squid setup is easier as it wont need memcached as squid keeps cached pages in memory and on disk. (memcached however would offer better scalability).
    regards georg

  3. kwiecień 10th, 2009 at 19:31 | #3

    Hi Georg, I do not have lot of experience with squid. I can tell what you can do with nginx and memacache. You can very flexible controle what is memcached and how. You can memcache user_int extension. You can flexible clear memcache after various user actions. You can set different memcache timeout within your extension. With upcoming version you can clear memcache of page, tree, user (all pages where particular user make some actions). We developed this extension for community website where content change every miniute. We found that lot of very high traffic website use memcache. Please find very intresting article about memcache and facebook http://www.facebook.com/note.php?note_id=23844338919.

  4. maj 7th, 2009 at 14:25 | #4

    Hi Bartosz,

    this sounds very interesting.
    What version of Typo3 is required for this extension?

    Best Regards,
    Rainer

  5. maj 7th, 2009 at 14:28 | #5

    4.2.X and higher
    We are going to publish new version next week.
    New version will work in two modes: with nginx and standalone (with small odifications of index.php)

  6. maj 7th, 2009 at 14:55 | #6

    Ah, OK.

    Thanks for the info!

  7. maj 15th, 2009 at 13:04 | #7

    Bartosz Aninowski :
    4.2.X and higher
    We are going to publish new version next week.
    New version will work in two modes: with nginx and standalone (with small odifications of index.php)

    Any news on this?
    ;-)

    Sorry for getting back to you on this and taking you on your word, but I find your project interesting.

    Best Regards,
    Rainer

  8. maj 15th, 2009 at 13:09 | #8

    Hi Rainer :)
    I try to upload new version till sunday. (till monday, edited on sunday :) )

  9. maj 18th, 2009 at 22:08 | #9

    I’m using Nginx on one of our servers for Magento, but recently thought about using it for TYPO3, too.

    Will try this out anytime soon. Thanks for the nice write-up!

  10. maj 18th, 2009 at 22:10 | #10

    There is a new version available. I will add new manual tomorrow. We’ve added lots of new features.

  11. Ironman
    maj 21st, 2009 at 19:59 | #11

    I wonder why you are still using Apache and do not run typo3 directly on nginx…any reason for that?

  12. maj 21st, 2009 at 20:09 | #12

    That’s depends on your architecture. I use nginx with 3 backend server, so Nginx works like load balancer. We had previous setup with apache so it was easer for us to add nginx as frontend server. I have also lower load with apache+mod_php5 than nginx+fastcgi or apacha+fastcgi. Anyway you can use nginx+memcache+fastcgi if you want.

  13. Markus Bischof
    czerwiec 4th, 2009 at 10:33 | #13

    First of all thank you for this really interesting article. I’m running a lot of Typo3-Sites on my server. Is there a way to have one nginx.conf which work for all my sites or is one config for each Typo3-Site a must have?

  14. czerwiec 4th, 2009 at 12:01 | #14

    You can have one config for all your site. That is no problem.

  15. Markus Bischof
    czerwiec 4th, 2009 at 12:46 | #15

    Maybe you have some hints for me? I’ve configured nginx, memcached and apache so far, that one page works find. What must be done to have your config working for all my domains? Are there some kind of variables for the domainname? I’m a little bit confused at the moment.

  16. lipiec 2nd, 2009 at 11:20 | #16

    I wrote an extension to add auto clearing of the cache if BE users make any changes on pages or content elements. If you are interested in embedding this functionality in your extension then please contact me. It is done with hooks. Additionally I found a small bug in the default mode of the module. Thanks for your great work. It is milestone for TYPO3 performance and quite easy to configure!

  17. lipiec 2nd, 2009 at 15:33 | #17

    Hi Alexander. Thanks for comments.
    Can you open bug report on Forge ?
    http://forge.typo3.org/projects/show/extension-evo_nginx_boost

  18. sierpień 17th, 2009 at 17:03 | #18

    Hi, I made a patch that fixes issues with php5-memcache-3.x (e.g. debian lenny)

    — class.tx_evo_nginx_boost.php.old 2009-08-12 06:58:55.000000000 +0200
    +++ class.tx_evo_nginx_boost.php 2009-08-12 07:05:00.000000000 +0200
    @@ -239,7 +239,19 @@
    */
    public function getServersStatistics($type = null, $slabid = null, $limit = 100)
    {
    - return $this->connected>0 ? $this->memcache->getExtendedStats($type, $slabid, $limit) : false;
    + /* patch (c) 2009 by Veit Nachtmann, veit@nachtmann.it
    + *
    + * $type cannot be null or the lib (>3.x) will throw an error. simple workaround.
    + */
    + if ($this->connected > 0) {
    + if (is_null($type)) {
    + return $this->memcache->getExtendedStats();
    + } else {
    + return $this->memcache->getExtendedStats($type, $slabid, $limit);
    + }
    + } else {
    + return false;
    + }
    }

    /**

  19. sierpień 17th, 2009 at 19:58 | #19

    Thanks for the path.
    We will put it soon.

  20. sierpień 20th, 2009 at 15:55 | #20

    I’m having trouble with this, everything misses the memcache (using nginx), and with the php-approach, every page stays blank…
    any hints?

  21. sierpień 20th, 2009 at 15:58 | #21

    Do you have any record in CacheDump section?

  22. Feelx
    sierpień 21st, 2009 at 17:07 | #22

    Hi, great work!
    It’s very interesting and I tried nginx to serve the TYPO3 rendered pages. It gives me 50% more speed (while no load). Parsing time is about 35ms instead of 70ms.
    But what I wonder is what port to you bind apache to? You write nothing about that, and is there no conflict, if apache and nginx listen to Port80?
    Thank you
    Greetings
    Feelx

  23. sierpień 21st, 2009 at 17:32 | #23

    You can setup apache to listen on 127.0.0.1 port 82 and proxy nginx to mentioned port. Nginx is great tool to make load ballancer.
    I have big doubts if you can reduce time by 50% with nginx+php. Plase check this benchmark http://blog.a2o.si/2009/06/24/apache-mod_php-compared-to-nginx-php-fpm/
    Nginx+php+memcached this is the best way:)

  24. sierpień 24th, 2009 at 15:32 | #24

    hey, nevermind, I fixed it.
    I was using the wrong cache-key with nginx -.-, php failed for some other reason, now it works perfectly.
    I also use nginx to punch out static files, works IMHO much better than relying on apache to do the job (I have both on the same machine).
    Thanks you your work!

  25. sierpień 24th, 2009 at 17:37 | #25

    Great that you like and it and fix your problem :)

  26. wrzesień 2nd, 2009 at 16:13 | #26

    hi,

    after deploying it in our live-environment, I had to deactivate it again, because it slightly uses more CPU than bare typo3, so the load (which is at the edge right now), increased to 120 :(
    The problem are the cache-misses, it’s like 1:10, hit:miss. With 200 objects in the memcache. 30000 misses after 1 hour.

    How could I debug that?

    I guess this is a problem with cookies, aparently 90% of our users have them set, though I’m not sure. Tests with ab work perfectly, 2kreq/s at least. But on the live env, this just explodes ;)
    plz halp :D

  27. wrzesień 2nd, 2009 at 16:32 | #27

    nginx or php-aproach?

  28. wrzesień 2nd, 2009 at 16:40 | #28

    what you mean “…with cookies, aparently 90% of our users have them set,”?
    These are logged users? If yes, please turn off memcaching for logged users and check again. I need more info about your configuration.

  29. Tomaz Zaman
    wrzesień 7th, 2009 at 14:37 | #29

    Is there an option that USER_INT object would not be cached AT ALL? I have some plugins on my webpage that display user’s information based on IP (in footer, so basically every page has a USER_INT objact).

  30. wrzesień 7th, 2009 at 14:56 | #30

    No, ajax-based solution is your friend :)

  31. wrzesień 7th, 2009 at 17:34 | #31

    Hello,
    i wanted to try this nice extension. But when i try i get an error on my FE, it says that the tx_evo_nginx_boost_index_conf.php is not there.

    I wrote in my index.php:

    require_once(’typo3conf/ext/evo_nginx_boost/tx_evonginxboost_index.php’);

    And then it says on line 6, the file is not there and this is the conf. file.

    What should i do?

    P.S.: I dont got NGINX server on my server.

  32. wrzesień 7th, 2009 at 18:15 | #32

    @louS
    After you add
    require_once(’typo3conf/ext/evo_nginx_boost/tx_evonginxboost_index.php’); to inde.php go to extension manager and set extendTypo3indexphp to 1 in evo_nginx_boost configuration then press update. Required file should be created.

  33. wrzesień 7th, 2009 at 18:35 | #33

    Hmm i did, now i get this error:

    Fatal error: Class ‘Memcache’ not found in /typo3conf/ext/evo_nginx_boost/class.tx_evo_nginx_boost.php on line 17

  34. wrzesień 7th, 2009 at 18:36 | #34

    @louS
    pecl install memcache
    you don’t have php-memcache

  35. wrzesień 7th, 2009 at 18:46 | #35

    Ah ok ;D

    Its hard to install on my server?

  36. wrzesień 7th, 2009 at 18:48 | #36

    @louS
    This is very simple task. Howere you must contact your server administrator to install php-memcache.
    Can’t help you with that :)

  37. wrzesień 7th, 2009 at 18:50 | #37

    Ok sure no prob :D

    Do i have to do something else after i installed php memcache?

  38. wrzesień 7th, 2009 at 18:52 | #38

    Ah i forgot to tell you, when i click on “Evo Nginx Boost” in my typo3 menu, i just see a blank site :D

  39. wrzesień 7th, 2009 at 18:55 | #39

    1. install memcached server
    2. install php-memcache
    3. restart web serwer
    4. install evo_nginx_boost
    5. add require_once to index.php
    6. set extendTypo3indexphp to 1 and update configuration
    7. seat and watch :)
    p.s if something go wrong, check webserver error log,

  40. wrzesień 7th, 2009 at 19:00 | #40

    memcached server?

    You sad i just need to install php memcache? :D

  41. wrzesień 7th, 2009 at 19:03 | #41

    Ah never mind, i cant install php memcache :( I asked already

  42. wrzesień 7th, 2009 at 19:04 | #42

    memcached server and php-memcache
    please use google :)

  43. JOsh
    wrzesień 14th, 2009 at 21:56 | #43

    I don’t see the error reporting line in any index.php file. I see it in Typo3/init.php should I add it there? I have tried and I keep getting a fatal error:

    Warning: Division by zero in /home/mosaics/public_html/typo3/init.php on line 69

    Warning: require_once(php’) [function.require-once]: failed to open stream: No such file or directory in /home/mosaics/public_html/typo3/init.php on line 69

    Fatal error: require_once() [function.require]: Failed opening required ‘php’’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/mosaics/public_html/typo3/init.php on line 69

  44. JOsh
    wrzesień 14th, 2009 at 22:09 | #44

    Put the line in typo3/index.php at line 65 and it seem to work and is waayy fast!

  45. wrzesień 14th, 2009 at 22:15 | #45

    lin 65 is ok too, but better at top of index.php :)
    I am glad that you like it. Regards.

  46. wrzesień 16th, 2009 at 11:58 | #46

    Witam,
    ostatnio proboje przyspieszyc jedna strone ktora ma wg. opisu zrobiona ta konfiguracje, jednak zastanawiam sie dlaczego w katalogu typo3temp/cache_pages mam pare giga danych , a w memcached znacznie mniej.
    Czy jest w ogole sens tego katalogu ?
    da sie to jakos wylaczyc by siedzialo to tylko i wylacznie w memcached ?

    oczywiscie mowie o typo3 4.2 , przy 4.3 to wiem jak to zrobic, jednak jest wciaz w wersji alpha.

    Dziekuje z gory za odpowiedz.

  47. wrzesień 16th, 2009 at 12:10 | #47

    nie da się wyłączyć ponieważ nasze rozwiązanie nie jest zamiennikiem, jeśli w memcached skończy się miejsce które zaplanowałeś, wtyczka będzie nadpisywać rekordy przeterminowane. O ile dobrze pamiętam w wersji 4.2 typo3 nie posiada garbage collectora i nie zajmuje się usuwaniem wyexpirowanych rekordów. Możesz to zrobić sam pisząc odpowiedni moduł albo usuwać cały cache w nocy. Oczywiście zależy to od wielu czynników.

  48. maj 21st, 2010 at 18:09 | #48

    Hi bart
    Is nginx compatible with 4.4.0beta2+?
    andi

  49. Bart
    maj 21st, 2010 at 18:17 | #49

    Yes It is.

  1. kwiecień 15th, 2009 at 22:59 | #1
  2. lipiec 19th, 2009 at 18:45 | #2