O documento descreve a nova arquitetura do Cartola FC para suportar maior volume de acessos de forma escalável. A arquitetura foi atualizada em 2016 para se centralizar na API, utilizando Golang, e melhorar a performance. As principais tecnologias utilizadas incluem Tsuru, Galeb e MySQL com réplicas.
2. Alexandre Saboia Fuziyama
Bacharel em Informática pela PUC-Rio
11 anos na globo.com
Full Stack Web Developer
9 anos trabalhando em equipes ágeis
@alexandresaboia saboia@corp.globo.com
21. Stackresumida
I N F R A EST R U T U R A
RPAAS Galeb Tsuru
Cartola
Comoé
UsuárioCartoleiro
22. Stackresumida
I N F R A EST R U T U R A
tsuru
PaaS-PlataformasaService
OrquestraçãodecontainersDocker
Rápido,FácileContinuousDeployment
Facilitaamanutençãoeconfiguraçãodainfraestrutura
Escalável,ConfiáveleOpensource
Suportaváriaslinguagens
Aproximadodesenvolvedordainfraestrutura
maisdetalhesem:https://tsuru.io
23. Stackresumida
I N F R A EST R U T U R A
tsuru
Usuário
Cartoleiro
Galeb
RouterL7
Unit
Unit
Unit
VM
Unit
Unit
Unit
VM
Unit
Unit
Unit
Unit
VM
máquinafísica
RPAAS
24. Stackresumida
I N F R A EST R U T U R A
Comoé
RPAAS Galeb Tsuru
Cartola
UsuárioCartoleiro
25. Stackresumida
I N F R A EST R U T U R A
Comoé
RoutereLoadBalancerdinâmicodenível7
Altamenteescalável
Permitetrocasderotaseconfigsemrestartoureload
Opensource
Auxiliaotsururefazendorotasparaasnovasunit
maisdetalhesem:http://galeb.io
Galeb
26. Stackresumida
I N F R A EST R U T U R A
Unit
Galeb
Usuário
Cartoleiro
Unit
Unit
Unit
Unit
Unit
Unit
Galeb
RouterL7
Unit
Unit
Unit
VM
VM
VM
RPAAS
27. Stackresumida
I N F R A EST R U T U R A
Comoé
RPAAS Galeb Tsuru
Cartola
UsuárioCartoleiro
28. Stackresumida
I N F R A EST R U T U R A
RPaaS
RPaaS-ReverseProxyasaService
PlugindisponívelparaoTsuru
NGINXcomproxyreversoparaasuaaplicação
RespeitaosheadersdefinidosnaaplicaçãoRPAAS
29. Usuário RPAAS Galeb Tsuru
Cartoleiro
unit
Stack
I N F R A EST R U T U R A
Fluxodetalhadodeumarequisição
unit
unit
unit
unit
unit
unit
unit
BF BB
30. https
I N F R A EST R U T U R A
apartirde2016
FullTLS
100% dos acessos no CDA é feito via https
34. Bancodedados
I N F R A EST R U T U R A
mudançaparaoMySQL5.7
pré-processadordequeriesmaiseficiente:ganhamos
maiorvelocidadenaexecução
replicaçãopormulti-thread:reduçãonotempode
replicaçãoentreomastereosslaves.
35. Bancodedados
I N F R A EST R U T U R A
MySQL5.7
+820gb
dados + índices na 32ª rodada
36. Bancodedados
I N F R A EST R U T U R A
MySQL5.7-replicaçãomaster/slave
read.cartola.mysql.interno.com
write.cartola.mysql.interno.com
READ READREAD
VIP de leitura
READ WRITE
VIP de escrita
read.cartola.mysql.interno.com
write.cartola.mysql.interno.com
37. Bancodedados
I N F R A EST R U T U R A
MySQL5.7-partitioning
CREATE TABLE members (
firstname VARCHAR(25) NOT NULL,
lastname VARCHAR(25) NOT NULL,
username VARCHAR(16) NOT NULL,
email VARCHAR(35),
joined DATE NOT NULL
)
PARTITION BY RANGE( YEAR(joined) ) (
PARTITION p0 VALUES LESS THAN (1960),
PARTITION p1 VALUES LESS THAN (1970),
PARTITION p2 VALUES LESS THAN (1980),
PARTITION p3 VALUES LESS THAN (1990),
PARTITION p4 VALUES LESS THAN MAXVALUE
);
https://dev.mysql.com/doc/refman/5.7/en/partitioning-types.html
members
p0
p1
p4
p3
p2. . .
38. Bancodedados
I N F R A EST R U T U R A
MySQL5.7-cuidadocomocrescimentodatabela
ALTER TABLE time_atleta MODIFY time_atleta_id bigintunsigned
NOT NULL AUTO_INCREMENT;
CREATETABLE`time_atleta`(
`time_atleta_id`int(11)unsignedNOTNULLAUTO_INCREMENT,
`rodada_id`tinyint(3)unsignedNOTNULL,
…
);
15horas!
40. Backend
I N F R A EST R U T U R A
tecnologiasutilizadasnaapi
golang
41. Backend
I N F R A EST R U T U R A
tecnologiasutilizadasnaapi
golang
https://www.tiobe.com/tiobe-index/go/
September 2017
2015.1
42. Backend
I N F R A EST R U T U R A
mudançaparaogolang
resultadosiniciais:
python: 4.500r/s
golang:14.000r/s
observações:
• concorrência
• aproveitamentoderecursos
testesapi
pythonxgolang
*emumamesmamáquinafísicasemcacheestático
43. Backend
I N F R A EST R U T U R A
mudançaparaogolang
40%
deeconomiaemCPU
2015 -2016
44. Backend
I N F R A EST R U T U R A
mudançaparaogolang
2015 -2017
23%
deeconomiaemCPU
45. Backend
I N F R A EST R U T U R A
mudançaparaogolang
conexões: 2015=140k 2016=1.1M 2017=1.2M
160milreq/seg 100milreq/seg
8xmais
conexõessimultâneas
2015 -2017
46. Backend
I N F R A EST R U T U R A
mudançaparaogolang
9xmais
usuáriossimultâneos
noGA 2015=100k 2016=493k 2017=905k
2015 -2017
48. Backend
I N F R A EST R U T U R A
estratégiaparacacheamento
Usuário
Cartoleiro
RPAAS Tsuru
Cartola
cacheadonorpaasrespeitandoomax-age
...
READ
49. Backend
I N F R A EST R U T U R A
cacheamentocache-control-maxAge
func WriteCachedResponse(w http.ResponseWriter, data interface{}, statusCode int, maxAge string) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.Header().Set("Vary", "Accept-Encoding")
w.Header().Set("Cache-Control", maxAge)
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(&data)
}
func WriteResponse(w http.ResponseWriter, data interface{}, statusCode int) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
w.Header().Set("Vary", "Accept-Encoding")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(&data)
}
50. Backend
I N F R A EST R U T U R A
estratégiaparacacheamento
Usuário
Cartoleiro
RPAAS Tsuru
Cartola
cacheadonomemcached
aplicação
...
READ
51. Backend
I N F R A EST R U T U R A
estratégiaparacacheamento
Usuário
Cartoleiro
RPAAS Tsuru
Cartola
requisiçãocompleta-recuperandodobancodedados
...
READ
52. Backend
I N F R A EST R U T U R A
estratégiaparacacheamento-fragmentaçãoporobjetoselistas
“time_id”: {[atleta_id,atleta_id,…]}
ex.: “1234” : {[1,2,3,4,5,6,7,8,9,10,11,12] }
"atleta_id": {“id”:1, “nome”:“RomáriodeSouzaFaria”,…}
“liga_id”: {[time_id,time_id,…]}
ex.: “5678” : {[11,22,33,44,55,66,77,88,99,110,111,112] }
"time_id": {“id”:11, “nome”:“PregerebaFC”,“slug”:“pregereba-fc”,…}
53. Backend
I N F R A EST R U T U R A
utilizaçãodeworkers
Recuperaçãodosatletasdomercado
Recuperaçãodosdadosdotime
http://divan.github.io/posts/go_concurrency_visualize/
fan-out pattern
54. Backend
I N F R A EST R U T U R A
utilizaçãodefilas
ManipulaçãodosSVGsdeescudosecamisas
Indexaçãodetimeseligasnabusca(ES)
Notificaçãopush
55. Backend
I N F R A EST R U T U R A
tempomáximoparauma conexão
10seg
éobastante!
normalmenteasrequisiçõesduramentre10mse100ms
56. Backend
I N F R A EST R U T U R A
estratégiaquerysnoMySQL
Queryssimplescompoucosjoins
Poucosupdates,prefiradelete+insert
Junteosdadosnaaplicação
57. Backend
I N F R A EST R U T U R A
gzipnaaplicação
n := negroni.New(negroni.NewRecovery(), gzip.Gzip(gzip.BestSpeed), Cors())
const (
NoCompression = flate.NoCompression
BestSpeed = flate.BestSpeed
BestCompression = flate.BestCompression
DefaultCompression = flate.DefaultCompression
HuffmanOnly = flate.HuffmanOnly
)
58. Backend
I N F R A EST R U T U R A
bibliotecasimportantes
GorillaMux
Testfy
jarcoal/httpmock.v1
logrus
guregu/null.v3
redis.v4
github.com/codegangsta/negroni
github.com/dropbox/godropbox/memcache
github.com/phyber/negroni-gzip/gzip
github.com/go-sql-driver/mysql
github.com/jmoiron/sqlx
60. Frontend
I N F R A EST R U T U R A
apostasemumSPA
• aplicaçãoestática
• reusodecomponentes
• comunicaçãocomocartolasomenteviaapi
• reduçãonaquantidadederequests
61. Frontend
I N F R A EST R U T U R A
porquêAngularJS?
• umframeworkmvccomtudoqueprecisaríamosparacriara
navegaçãodocartola
• implementaçãodefluxosmaisexplícito
• organizaçãodocódigo(lógicadenegócio,camadade
apresentação)
• facilidadenacomunicaçãoentrecomponentesnamesmapágina
62. Frontend
I N F R A EST R U T U R A
vantagensdoAngularJS?
problemasconhecidos
63. Frontend
I N F R A EST R U T U R A
outrasestratégias
• usodeSVGparaamaioriadasimagensdogameweb
• utilizaçãodespritessvg
64. Frontend
I N F R A EST R U T U R A
outrasestratégias
• minifyhtml
• minifycss
• otimizadorparaimagens
• svgsprite
tasksGulp
65. Frontend
I N F R A EST R U T U R A
CDN
NGINXdoRpaaSésuperperformáticoparaaentregadeestático
usamosumaappestáticanotsuruparafuncionarcomoumaCDN
Estratégiaparaversionamentodosdeploysevitandoocacheamento
nobrowserdousuário
https://cartolafc.globo.com/dist/1.1.7/js/main.js
https://cartolafc.globo.com/dist/1.1.7/css/cartola.css
https://cartolafc.globo.com/dist/1.1.7/img/logo_cartola.png
66. Takeaway
I N F R A EST R U T U R A
otimizaçãoeperformance
"Premature optimization is the root of all evil."
DonaldKnuth