El documento habla sobre cómo optimizar aplicaciones y bases de datos para evitar que "mueran de éxito" ante un aumento repentino de tráfico. Recomienda optimizar el código de la aplicación, la base de datos subyacente y escalar fácilmente para poder crecer. Algunas técnicas para optimizar la base de datos incluyen usar índices, cachés como la caché de consultas y buffers, y actualizar el software y hardware.
1. No Mueras de Éxito
Victor Jimenez <vjimenez@warp.es>
Giuseppe Maxia <datacharmer@sun.com>
Hola, soy Víctor Jimenez, y voy a ser vuestro ponente durante los próximos 40 minutos.
Tenemos el honor de contar con el único, el inigualable, el domador de bytes, el encantador
de datos... Giuseppe Maxia, que nos acompaña en esta presentación.
2. Decimos que una aplicación ha muerto de éxito, cuando se hace popular y de repente recibe más visitas de las que puede
soportar.
Como la gallina de los huevos de oro, todo el mundo quería tocarle los huevos...
3. ... y dijo "Ya no puedo más".
Igual hace nuestro servidor, cuando recibe muchos usuarios de vez, dice "Ya no más" y se cuelga.
4. Pasos para no morir
de éxito:
•Optimizar la aplicación
•Optimizar la base de datos
•Escalar fácilmente
Si queremos que nuestra aplicación no muera de éxito, tenemos que seguir estos pasos en orden.
Optimizar la aplicación: Normalmente nuestro primer código no suele ser muy óptimo.
Optimizar la base de datos: Hacer que nuestra base de datos no sea un cuello de botella.
Escalar fácilmente: Prepararnos para crecer en un futuro.
5. Optimización
•Hacer más con lo mismo
•Objetivo: Aumentar consultas/sec
•¿Cómo?: Menor tiempo de ejecución
Optimizar es hacer más con lo mismo que ya tenemos.
Aplicado a la base de datos, vamos a querer aumentar la cantidad de consultas que un servidor puede ejecutar.
Para ello, intentaremos reducir el tiempo de ejecución de las consultas.
6. Optimización
0s 1s 2s 3s 4s 5s 6s 7s 8s 9s
Tenemos una consulta que tarda 2,5 segundos en ejecutarse si se ejecuta sola.
Pero lo normal es que esa consulta se ejecute en varios procesos en paralelo.
7. Optimización
0s 1s 2s 3s 4s 5s 6s 7s 8s 9s
Dado que la máquina tiene más recursos ocupados, es posible que tarde más en ejecutarse.
En este caso, se ha ejecutado la consulta cinco veces en paralelo, cada una un segundo más tarde que la anterior.
8. Optimización
C=5
0s 1s 2s 3s 4s 5s 6s 7s 8s 9s
En un momento se están ejecutando 5 consultas a la vez.
El servidor necesita poder soportar estos picos.
9. Optimización
C max = 1
0s 1s 2s 3s 4s 5s 6s 7s 8s 9s
Si optimizamos esas consultas para que tarden medio segundo...
10. Optimización
C max = 1
0s 1s 2s 3s 4s 5s 6s 7s 8s 9s
... sólo se ejecuta una consulta cada vez.
Reduciendo el nivel de concurrencia que tiene que soportar el servidor.
11. Optimización
0s 1s 2s 3s 4s 5s 6s 7s 8s 9s
Dejando muchos más recursos libres.
12. Optimización
•Normalización
•Índices
•Cachés
•Buffers
•Actualizaciones de Software
•Mantenimiento
•Motor de Bases de datos
Hay muchas cosas que se pueden hacer para optimizar una base de datos, vamos a hablar sobre algunas de ellas.
13. Índices
table.MYI
table.MYD
Los índices nos permiten acceder más rápido a los datos.
Si indexamos una columna, se guarda una copia aparte, ordenada en una estructura de árbol.
Buscar por un índice es la forma más rápida de llegar a una fila.
14. Índices InnoDB
En Innodb los índices apuntan a la clave primaria,
por tanto hay que elegir la clave primaria con sabiduría.
15. Cachés
•MyISAM Key Cache
•Query Cache
MySQL usa varias cachés que nos permiten cargar parte de los datos en memoria,
y así no leer del disco duro.
16. Query Cache
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
De normal, cuando un usuario ejecuta una consulta en MySQL,
MySQL tiene que interpretarla, saber qué quiere el usuario.
Luego la optimiza para ver cuál es la mejor manera de ejecutarla, usar un índice u otro, aplicar una condición antes que otra...
Y por último la ejecuta, para ello delega en los motores de bases de datos que interactúan directamente con los datos.
Todo ello supone una cantidad considerable de trabajo.
17. Query Cache
SELECT
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
De normal, cuando un usuario ejecuta una consulta en MySQL,
MySQL tiene que interpretarla, saber qué quiere el usuario.
Luego la optimiza para ver cuál es la mejor manera de ejecutarla, usar un índice u otro, aplicar una condición antes que otra...
Y por último la ejecuta, para ello delega en los motores de bases de datos que interactúan directamente con los datos.
Todo ello supone una cantidad considerable de trabajo.
18. Query Cache
SELECT
result
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
De normal, cuando un usuario ejecuta una consulta en MySQL,
MySQL tiene que interpretarla, saber qué quiere el usuario.
Luego la optimiza para ver cuál es la mejor manera de ejecutarla, usar un índice u otro, aplicar una condición antes que otra...
Y por último la ejecuta, para ello delega en los motores de bases de datos que interactúan directamente con los datos.
Todo ello supone una cantidad considerable de trabajo.
19. Query Cache
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
Si activamos la Query Cache,
la primera vez que ejecutemos la consulta seguirá los mismos pasos.
Con un paso adicional, a la vez que se devuelven los datos al usuario, se guarda una copia en la caché de consultas.
20. Query Cache
SELECT
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
Si activamos la Query Cache,
la primera vez que ejecutemos la consulta seguirá los mismos pasos.
Con un paso adicional, a la vez que se devuelven los datos al usuario, se guarda una copia en la caché de consultas.
21. Query Cache
SELECT
result
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
Si activamos la Query Cache,
la primera vez que ejecutemos la consulta seguirá los mismos pasos.
Con un paso adicional, a la vez que se devuelven los datos al usuario, se guarda una copia en la caché de consultas.
22. Query Cache
SELECT
result
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
Si activamos la Query Cache,
la primera vez que ejecutemos la consulta seguirá los mismos pasos.
Con un paso adicional, a la vez que se devuelven los datos al usuario, se guarda una copia en la caché de consultas.
23. Query Cache
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
La próxima vez que se ejecute la misma consulta,
se obtendrán los datos diréctamente de la cache.
Lo que es un proceso casi instantáneo.
24. Query Cache
SELECT
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
La próxima vez que se ejecute la misma consulta,
se obtendrán los datos diréctamente de la cache.
Lo que es un proceso casi instantáneo.
25. Query Cache
SELECT
result
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
La próxima vez que se ejecute la misma consulta,
se obtendrán los datos diréctamente de la cache.
Lo que es un proceso casi instantáneo.
26. Query Cache
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
¿Estos datos están siempre actualizados?
Sí, porque si se modifican los datos subyacentes, la caché se limpia.
27. Query Cache
UPDATE
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
¿Estos datos están siempre actualizados?
Sí, porque si se modifican los datos subyacentes, la caché se limpia.
28. Query Cache
UPDATE
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
¿Estos datos están siempre actualizados?
Sí, porque si se modifican los datos subyacentes, la caché se limpia.
29. Query Cache
UPDATE
MySQL server
SELECT result
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
¿Estos datos están siempre actualizados?
Sí, porque si se modifican los datos subyacentes, la caché se limpia.
30. Query Cache
UPDATE
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
¿Estos datos están siempre actualizados?
Sí, porque si se modifican los datos subyacentes, la caché se limpia.
31. Query Cache
MySQL server
Query Cache
Parse
Optimization
Execution
MyISAM InnoDB Memory
Tablas
¿Estos datos están siempre actualizados?
Sí, porque si se modifican los datos subyacentes, la caché se limpia.
32. Query Cache
!"#$%&'()&$*+,-./0102,/345,$6$7$8$9:;7$8$9:;7<
!='>$%&'()&$!#)#?!$&@A"$B*0102,CB<
DEEEEEEEEEEEEEEEEEEEEEEEEEDEEEEEEEEED
F$G1-41HI,/J1K,$$$$$$$$$$$F$G1I+,$$$F
DEEEEEEEEEEEEEEEEEEEEEEEEEDEEEEEEEEED
F$L0102,/M-,,/HIN0O3$$$$$$F$9$$$$$$$F$
F$L0102,/M-,,/K,KN-.$$$$$$F$79PQR77$F$
F$L0102,/24S3$$$$$$$$$$$$$F$:$$$$$$$F$
F$L0102,/4J3,-S3$$$$$$$$$$F$:$$$$$$$F$
F$L0102,/INTK,K/U-+J,3$$$$F$:$$$$$$$F$
F$L0102,/JNS/0102,V$$$$$$$F$:$$$$$$$F$
F$L0102,/*+,-4,3/4J/0102,$F$:$$$$$$$F$
F$L0102,/SNS1I/HIN0O3$$$$$F$9$$$$$$$F$
DEEEEEEEEEEEEEEEEEEEEEEEEEDEEEEEEEEED
Para activar la caché de consultas, le asignamos un tamaño en la variable...
Disponemos de varias variables de estado de la query cache.
Importante, la Qcache_hits, que son las veces que una consulta se lee de la caché.
33. Query Cache
?31W,$6$L0102,/24S3$X$YL0102,/24S3$D$Z'[/3,I,0S
!='>$%&'()&$!#)#?!$&@A"$BL0102,/24S3B<
DEEEEEEEEEEEEEEEEEEEEEEEEEDEEEEEEEEED
F$L0102,/24S3$$$$$$$$$$$$$F$:$$$$$$$F$
DEEEEEEEEEEEEEEEEEEEEEEEEEDEEEEEEEEED
!='>$%&'()&$!#)#?!$&@A"$BZ'[/3,I,0SB<
DEEEEEEEEEEEEEEEDEEEEEEED
F$ZNK/3,I,0S$$$$F$;$$$$$F$
DEEEEEEEEEEEEEEEDEEEEEEED
La variable de estado COM_select muestra las consultas que se han ejecutado completamente.
Así que dividiendo los aciertos de la cache entre el total de consultas que se ejecutan, obtenemos el uso de la cache.
34. Buffers
Los bu!ers son areas de memoria que MySQL reserva temporalmente para hacer algunas operaciones,
como por ejemplo ordenar los resultados de una consulta.
35. Buffers
MySQL server
MySQL
MyISAM
Hard Disk
table on Disk
Al ejecutar una consulta con un ORDER BY
Se leen los datos de la tabla, y se crea un bu!er en memoria para ordenar los resultados.
36. Buffers
SELECT ... ORDER BY ...
MySQL server
MySQL
MyISAM
Hard Disk
table on Disk
Al ejecutar una consulta con un ORDER BY
Se leen los datos de la tabla, y se crea un bu!er en memoria para ordenar los resultados.
37. Buffers
SELECT ... ORDER BY ...
MySQL server
MySQL
MyISAM
Hard Disk
table on Disk
Al ejecutar una consulta con un ORDER BY
Se leen los datos de la tabla, y se crea un bu!er en memoria para ordenar los resultados.
38. Buffers
SELECT ... ORDER BY ...
MySQL server
Sort Buffer
MySQL
R U S L T E
MyISAM
Hard Disk
table on Disk
Al ejecutar una consulta con un ORDER BY
Se leen los datos de la tabla, y se crea un bu!er en memoria para ordenar los resultados.
39. Buffers
SELECT ... ORDER BY ...
MySQL server
Sort Buffer
MySQL
R E S U L T
MyISAM
Hard Disk
table on Disk
Una vez ordenados, se devuelven al usuario.
40. Buffers
SELECT ... ORDER BY ...
result
MySQL server
Sort Buffer
MySQL
R E S U L T
MyISAM
Hard Disk
table on Disk
Una vez ordenados, se devuelven al usuario.
41. Buffers
MySQL server
Sort Buffer
MySQL
MyISAM
Hard Disk
table on Disk
Una vez ordenados, se devuelven al usuario.
42. Buffers
MySQL server
MySQL
Sort Buffer
MyISAM
Hard Disk
table on Disk
Si el bu!er es más reducido
43. Buffers
MySQL server
MySQL
Sort Buffer
MyISAM
Hard Disk
table on Disk
puede que mysql no tenga espacio suficiente para realizar la ordenación
44. Buffers
SELECT ... ORDER BY ...
MySQL server
MySQL E
R U S Buffer
Sort L T
MyISAM
Hard Disk
table on Disk
puede que mysql no tenga espacio suficiente para realizar la ordenación
45. Buffers
SELECT ... ORDER BY ...
MySQL server
MySQL E
R U S Buffer
Sort L T
MyISAM
Hard Disk
table on Disk
puede que mysql no tenga espacio suficiente para realizar la ordenación
46. Buffers
SELECT ... ORDER BY ...
MySQL server
MySQL
Sort Buffer
MyISAM
Hard Disk
table on Disk R U S L T E
teniendo que mover los datos al disco, que es mucho más lento.
Esto influirá negativamente en el rendimiento.
47. Buffers
SELECT ... ORDER BY ...
MySQL server
MySQL
Sort Buffer
MyISAM
Hard Disk
table on Disk R E S U L T
48. Buffers
SELECT ... ORDER BY ...
result
MySQL server
MySQL
Sort Buffer
MyISAM
Hard Disk
table on Disk R E S U L T
49. Buffers
El tamaño del bu!er está gobernado por la variable sort_bu!er_size.
Por defecto es de 2MB.
Cuidado con este tamaño, ya que se creará por cada consulta que debe ser ordenada.
50. Buffers
!"#$%&'()&$3N-S/H+MM,-/345,$6$];$8$9:;7<
El tamaño del bu!er está gobernado por la variable sort_bu!er_size.
Por defecto es de 2MB.
Cuidado con este tamaño, ya que se creará por cada consulta que debe ser ordenada.
51. Buffers
!"#$%&'()&$3N-S/H+MM,-/345,$6$];$8$9:;7<
^^$#1K1_N$UN-$ZNJ3+IS1$``
El tamaño del bu!er está gobernado por la variable sort_bu!er_size.
Por defecto es de 2MB.
Cuidado con este tamaño, ya que se creará por cada consulta que debe ser ordenada.
52. Actualizaciones
Source:
http://datacharmer.blogspot.com/2009/04/mysql-54-performance-with-logging.html
Algunas actualizaciones de software aumentan el rendimiento,
como es el caso de MySQL 5.4, que escala mejor en máquinas con varios núcleos
53. Actualizaciones
x 1.59
Source: http://dev.mysql.com/tech-resources/articles/mysql-54.html
Y que en algunos casos puede ser hasta un 59% más rápido que 5.1
55. Herramientas
•Slow-queries log
•EXPLAIN
•Enterprise Manager
Sabemos solucionar algunos problemas,
¿pero cómo sabemos qué problemas tenemos?
Vamos a ver algunas herramientas para detectar problemas.
56. Slow-queries log
•Tiempo de ejecución alto
•Consultas que no están utilizando índices
El registro de consultas lentas...
57. Slow-queries log
aK.3*IVb
INWE3INTE*+,-4,3
INJW/*+,-./S4K,$6$9
INWE*+,-4,3EJNSE+34JWE4JV,c,3
d$K.3*IV+KU3INT$X+3-XIN01IXK.3*IXK.3*I/3INTeINW
El log de consultas lentas se activa con las opciones de configuración...
long_query_time son los segundos que tiene que tardar una consulta para que se considere lenta. Por defecto son 10 segundos.
Podemos ver resumido el log de consultas lentas con mysqldumpslow
59. EXPLAIN
TN-IVf$"gh&)@i$!"&"Z#$ZNV,j$i1K,$
$$$$$$$$$$$$$$$$$$$kl'[$ZN+JS-.$
$$$$$$$$$$$$$$$$$$$>="l"$ZNJS4J,JS$6$B"+-NU,Bm%
888888888888888888888$9e$-NT$888888888888888888888
$$$$$$$$$$$4Vn$9
$$3,I,0S/S.U,n$!@[h&"
$$$$$$$$S1HI,n$ZN+JS-.
$$$$$$$$$S.U,n$)&&
UN334HI,/O,.3n$i?&&
$$$$$$$$$$O,.n$i?&&
$$$$$$O,./I,Jn$i?&&
$$$$$$$$$$-,Mn$i?&&
$$$$$$$$$-NT3n$;o;
$$$$$$$$"cS-1n$?34JW$T2,-,
Con el comando EXPLAIN podemos saber qué va a hacer el optimizador...
En este caso se han seleccionado los países de Europa. Explain nos dice que se va a Escanear toda la tabla (type: ALL), que no se
van a utilizar todas las claves (key: NULL), y que se van a leer 252 filas (rows: 252).
Si estuvieramos ordenando y usáramos el disco para ello, lo marcaría en el campo Extra como "using filesort".
60. EXPLAIN
TN-IVf$"gh&)@i$!"&"Z#$ZNV,j$i1K,$
$$$$$$$$$$$$$$$$$$$kl'[$ZN+JS-.$
$$$$$$$$$$$$$$$$$$$>="l"$ZNV,$&@A"$B)CBm%
888888888888888888888$9e$-NT$888888888888888888888
$$$$$$$$$$$4Vn$9
$$3,I,0S/S.U,n$!@[h&"
$$$$$$$$S1HI,n$ZN+JS-.
$$$$$$$$$S.U,n$-1JW,
UN334HI,/O,.3n$hl@[)lp
$$$$$$$$$$O,.n$hl@[)lp
$$$$$$O,./I,Jn$]
$$$$$$$$$$-,Mn$i?&&
$$$$$$$$$-NT3n$9q
$$$$$$$$"cS-1n$?34JW$T2,-,
Con esta otra consulta podemos ver que se va a usar un índice...
Seleccionamos países cuyo código empieza por A.
No escaneamos toda la tabla, sino un rango (type: range), los países entre Axx y Bxx.
Usamos la clave primaria (key: PRIMARY), que es la columna Code.
Se van a escanear sólo 18 filas (rows: 18). Que es un 5% de las consultas anteriores.
61. Enterprise Monitor
•Disponible con MySQL Enterprise
•Monitorización de servidores
•Solución de problemas
•Query Analizer
Otra herramienta para detectar errores es el MySQL Enterprise Monitor.
El Enterprise Monitor monitoriza el estado de nuestros servidores MySQL.
Una de las partes del EM es Query Analizer, que analiza todas las consultas que se ejecutan en un servidor y detecta las que
pueden ser problemáticas...
62. Enterprise Monitor
Consultas SQL
Application
MySQL Server
Estado Servidores
Agent
MySQL
MySQL Server
Enterprise Monitor
Agent
¿Cómo funciona el Enterprise Manager?
En un servidor tenemos la aplicación Enterprise Monitor.
Por cada servidor MySQL tendremos un agente que lo irá monitorizando y enviará los datos al Enterprise Monitor.
63. Enterprise Monitor
Consultas SQL
Application
MySQL Server
Estado Servidores
Agent
MySQL
MySQL Server
Enterprise Monitor
Agent
¿Cómo funciona el Enterprise Manager?
En un servidor tenemos la aplicación Enterprise Monitor.
Por cada servidor MySQL tendremos un agente que lo irá monitorizando y enviará los datos al Enterprise Monitor.
64. Enterprise Monitor
Consultas SQL
Application
MySQL Server
Estado Servidores
Agent
MySQL
MySQL Server
Enterprise Monitor
Agent
¿Cómo funciona el Enterprise Manager?
En un servidor tenemos la aplicación Enterprise Monitor.
Por cada servidor MySQL tendremos un agente que lo irá monitorizando y enviará los datos al Enterprise Monitor.
65. Enterprise Monitor
Consultas SQL
Application Agent
MySQL Server
(Proxy)
Estado Servidores Estadísticas Consultas
MySQL Agent
MySQL Server
Enterprise Monitor (Proxy)
(Query Analizer)
Para filtrar las consultas que se ejecutan en un servidor, el Agente actúa como un proxy.
66. Enterprise Monitor
Consultas SQL
Application Agent
MySQL Server
(Proxy)
Estado Servidores Estadísticas Consultas
MySQL Agent
MySQL Server
Enterprise Monitor (Proxy)
(Query Analizer)
Para filtrar las consultas que se ejecutan en un servidor, el Agente actúa como un proxy.
67. Enterprise Monitor
Consultas SQL
Application Agent
MySQL Server
(Proxy)
Estado Servidores Estadísticas Consultas
MySQL Agent
MySQL Server
Enterprise Monitor (Proxy)
(Query Analizer)
Para filtrar las consultas que se ejecutan en un servidor, el Agente actúa como un proxy.
68. Escalabilidad
•Hacer más con más hardware
•Objetivo: Aumentar consultas/sec
•¿Cómo?: Aumentar concurrencia
Cuando ya no podemos sacarle más rendimiento a lo que tenemos, es hora de cambiar.
Entendemos como escalabilidad al hecho de obtener más rendimiento ampliando el hardware.
69. Escalabilidad
100 GB HDD
2 GB RAM
2GHz CPU
x2 cores
Hay dos formas de escalar.
La primera consiste en mejorar el servidor de la aplicación.
70. Escalabilidad
Escalado Vertical 500 GB HDD
x2 (RAID)
100 GB HDD 8 GB RAM
2 GB RAM
3GHz CPU
2GHz CPU x8 cores
x2 cores
Hay dos formas de escalar.
La primera consiste en mejorar el servidor de la aplicación.
71. Escalabilidad
100 GB HDD
2 GB RAM
2GHz CPU
x2 cores
De nuevo, comprar una máquina más grande es algo tan sencillo, que puede hacerlo el mono de la empresa.
72. Escalabilidad
100 GB HDD
2 GB RAM
2GHz CPU
x2 cores
Otra forma de escalar consiste en comprar más máquinas igules a las que ya tenemos.
Y sobre ellas, ejecutar algún servicio que aproveche varias máquinas.
Como la replicación.
73. Escalabilidad
Escalado Horizontal
100 GB HDD 100 GB HDD 100 GB HDD
2 GB RAM 2 GB RAM 2 GB RAM
2GHz CPU 2GHz CPU 2GHz CPU
x2 cores x2 cores x2 cores
Otra forma de escalar consiste en comprar más máquinas igules a las que ya tenemos.
Y sobre ellas, ejecutar algún servicio que aproveche varias máquinas.
Como la replicación.
74. Escalabilidad
Escalado Horizontal
MySQL Master MySQL Slave MySQL Slave
100 GB HDD 100 GB HDD 100 GB HDD
2 GB RAM 2 GB RAM 2 GB RAM
2GHz CPU 2GHz CPU 2GHz CPU
x2 cores x2 cores x2 cores
Otra forma de escalar consiste en comprar más máquinas igules a las que ya tenemos.
Y sobre ellas, ejecutar algún servicio que aproveche varias máquinas.
Como la replicación.
75. Replicación
MySQL Master MySQL Slave
Binary Log
Tabla Tabla
Tenemos un servidor Maestro y uno esclavo.
Se inserta en el maestro, y se registra en el log binario
Periódicamente, el esclavo pedirá los últimos cambios al Maestro
Conforme los reciba, los aplicará en sus tablas
El resultado es que tanto el maestro como el esclavo mantienen los mismos datos
76. Replicación
INSERT
MySQL Master MySQL Slave
Binary Log
Tabla INSERT Tabla
Tenemos un servidor Maestro y uno esclavo.
Se inserta en el maestro, y se registra en el log binario
Periódicamente, el esclavo pedirá los últimos cambios al Maestro
Conforme los reciba, los aplicará en sus tablas
El resultado es que tanto el maestro como el esclavo mantienen los mismos datos
77. Replicación
INSERT
MySQL Master MySQL Slave
Binary Log INSERT
Tabla INSERT Tabla
Tenemos un servidor Maestro y uno esclavo.
Se inserta en el maestro, y se registra en el log binario
Periódicamente, el esclavo pedirá los últimos cambios al Maestro
Conforme los reciba, los aplicará en sus tablas
El resultado es que tanto el maestro como el esclavo mantienen los mismos datos
78. Replicación
MySQL Master MySQL Slave
Binary Log INSERT
Tabla INSERT Tabla
Tenemos un servidor Maestro y uno esclavo.
Se inserta en el maestro, y se registra en el log binario
Periódicamente, el esclavo pedirá los últimos cambios al Maestro
Conforme los reciba, los aplicará en sus tablas
El resultado es que tanto el maestro como el esclavo mantienen los mismos datos
79. Replicación
MySQL Master MySQL Slave
Binary Log INSERT
Tabla INSERT Tabla INSERT
Tenemos un servidor Maestro y uno esclavo.
Se inserta en el maestro, y se registra en el log binario
Periódicamente, el esclavo pedirá los últimos cambios al Maestro
Conforme los reciba, los aplicará en sus tablas
El resultado es que tanto el maestro como el esclavo mantienen los mismos datos
80. Replicación
MySQL Master MySQL Slave
Binary Log INSERT
Tabla INSERT Tabla INSERT
Tenemos un servidor Maestro y uno esclavo.
Se inserta en el maestro, y se registra en el log binario
Periódicamente, el esclavo pedirá los últimos cambios al Maestro
Conforme los reciba, los aplicará en sus tablas
El resultado es que tanto el maestro como el esclavo mantienen los mismos datos
81. Replicación
MySQL Master
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
Podemos aplicar la replicación en el caso de una aplicación con mucha carga de lectura.
En ese caso, tendremos un esclavo donde se realizarán las modificaciones de datos.
Y varios esclavos para consultar datos.
82. Replicación
INSERT MySQL Master
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
Podemos aplicar la replicación en el caso de una aplicación con mucha carga de lectura.
En ese caso, tendremos un esclavo donde se realizarán las modificaciones de datos.
Y varios esclavos para consultar datos.
83. Replicación
MySQL Master
SELECT
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
MySQL Slave
Podemos aplicar la replicación en el caso de una aplicación con mucha carga de lectura.
En ese caso, tendremos un esclavo donde se realizarán las modificaciones de datos.
Y varios esclavos para consultar datos.
84. Replicación Circular
1 2
MySQL Master for 2 MySQL Master for 3
MySQL Slave for 3 MySQL Slave for 1
3
MySQL Master for 1
MySQL Slave for 2
Se puede realizar una replicación circular si un esclavo replica cambios a un maestro.
Así podríamos soportar aplicaciones con cargas altas de escritura y lectura,
o podemos distribuír geográficamente nuestros datos.
85. MySQL Cluster
Otra forma de escalar horizontalmente es MySQL Cluster...
Tenemos los nodos de datos... Un nodo de gestión... Varios servidores MySQL...
Al insertar una fila... es el servidor MySQL en encargado de guardada en el cluster.
MySQL Cluster nos deja escalar añadiendo nodos en caliente...
MySQL Cluster escala muy bien y ofrece muy alta disponibilidad, pero requiere muchas máquinas para funcionar.
86. MySQL Cluster
MySQL Cluster
NDB NDB
NDB NDB
NDB NDB
Otra forma de escalar horizontalmente es MySQL Cluster...
Tenemos los nodos de datos... Un nodo de gestión... Varios servidores MySQL...
Al insertar una fila... es el servidor MySQL en encargado de guardada en el cluster.
MySQL Cluster nos deja escalar añadiendo nodos en caliente...
MySQL Cluster escala muy bien y ofrece muy alta disponibilidad, pero requiere muchas máquinas para funcionar.
87. MySQL Cluster
MySQL Cluster
NDB NDB
NDB NDB
NDB NDB
Management
Otra forma de escalar horizontalmente es MySQL Cluster...
Tenemos los nodos de datos... Un nodo de gestión... Varios servidores MySQL...
Al insertar una fila... es el servidor MySQL en encargado de guardada en el cluster.
MySQL Cluster nos deja escalar añadiendo nodos en caliente...
MySQL Cluster escala muy bien y ofrece muy alta disponibilidad, pero requiere muchas máquinas para funcionar.
88. MySQL Cluster
MySQL Cluster
MySQL NDB NDB
MySQL
NDB NDB
MySQL
NDB NDB
Management
Otra forma de escalar horizontalmente es MySQL Cluster...
Tenemos los nodos de datos... Un nodo de gestión... Varios servidores MySQL...
Al insertar una fila... es el servidor MySQL en encargado de guardada en el cluster.
MySQL Cluster nos deja escalar añadiendo nodos en caliente...
MySQL Cluster escala muy bien y ofrece muy alta disponibilidad, pero requiere muchas máquinas para funcionar.
89. MySQL Cluster
MySQL Cluster
INSERT MySQL NDB NDB
MySQL
NDB NDB
INSERT INSERT
MySQL
NDB NDB
Management
Otra forma de escalar horizontalmente es MySQL Cluster...
Tenemos los nodos de datos... Un nodo de gestión... Varios servidores MySQL...
Al insertar una fila... es el servidor MySQL en encargado de guardada en el cluster.
MySQL Cluster nos deja escalar añadiendo nodos en caliente...
MySQL Cluster escala muy bien y ofrece muy alta disponibilidad, pero requiere muchas máquinas para funcionar.
90. MySQL Cluster
MySQL Cluster
INSERT MySQL NDB NDB
MySQL
NDB NDB
INSERT INSERT
MySQL
NDB NDB
Management NDB NDB
Otra forma de escalar horizontalmente es MySQL Cluster...
Tenemos los nodos de datos... Un nodo de gestión... Varios servidores MySQL...
Al insertar una fila... es el servidor MySQL en encargado de guardada en el cluster.
MySQL Cluster nos deja escalar añadiendo nodos en caliente...
MySQL Cluster escala muy bien y ofrece muy alta disponibilidad, pero requiere muchas máquinas para funcionar.
91. Hemos visto muchas cosas para optimizar un servidor mysql...
Un consejo... ¡¡¡ No toques el servidor de producción !!!
Por muchos motivos...
92. ¡¡¡ No toques producción !!!
Hemos visto muchas cosas para optimizar un servidor mysql...
Un consejo... ¡¡¡ No toques el servidor de producción !!!
Por muchos motivos...
93. Preparar la migración
•Entorno de pruebas
•Posibilidad de volver atrás
Lo recomendable es probar las cosas siempre en un entorno controlado donde podamos volver atrás.
Para este entorno de pruebas, podemos usar MySQL Sandbox.
94. MySQL Sandbox
•one (unix) host
•many database servers
•single or multiple
sandboxes
•installs IN SECONDS
•Free software (GPL)
http://mysqlsandbox.net
MySQL Sandbox is a tool that installs an additional MySQL server in a few seconds.
You can have more than one database servers in your host, all of them independent from each other. Installing a new server with
MySQL Sandbox is a matter of seconds. You can install either a single sandbox or a system including multiple ones.
It is free software, and it works on most every unix system.
http://www.slideshare.net/datacharmer/mysql-sandbox-quick-demo
95. 1 host - many servers
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
96. 1 host - many servers
5.0.83
single
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
97. 1 host - many servers
5.1.35
5.0.83
single
single
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
98. 1 host - many servers
5.1.35
5.0.83
single
single
single
5.4.1
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
99. 1 host - many servers
5.1.35
5.0.83
single
single
5.0.82
master
5.0.82 5.0.82
slave slave
standard
replication
single
5.4.1
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
100. 1 host - many servers
5.1.35
5.1.35
5.0.83
single
single 5.4.1
5.0.83
5.0.82 group
master
5.0.82 5.0.82
slave slave
standard
replication
single
5.4.1
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
101. 1 host - many servers
5.1.35
5.1.35
5.0.83
single
single 5.4.1
5.0.83
5.0.82 group
master
5.1.34
5.0.82 5.0.82
slave slave 5.1.34
5.1.34
standard
replication circular 5.1.34
single
5.4.1 replication
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
102. 1 host - many servers
5.1.35
ALL
5.1.35
5.0.83
single
single 5.4.1
5.0.83
5.0.82 group
INDEPENDENT
master
5.1.34
5.0.82 5.0.82
slave slave 5.1.34
5.1.34
standard
replication circular 5.1.34
single
5.4.1 replication
HOST
When you need to test enterprise software, the database is a core component. For this, it's important to be able to have test
database servers in your host. You want to be able to test in di!erent conditions, possibly with di!erent versions.
With MySQL Sandbox, it's easy to create single servers of di!erent versions, or a replicated system with master and salves, or a
group of servers with various versions, or a circular replication system. You can have all of them, one by one , or all at once, and
they will not interfere with each other.
103. Installation
•as root
!"#$%&"'()*+,,)%&-./0
Installing MySQL Sandbox is easy. It is a Perl module. Getting it in your server is just a matter of typing one commend as root.
If you want, you can also install in the user space. The reference manual explains how to do it.
104. Creating a single
sandbox
•as normal user
!"1%2345%&-./0"6
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
Let's make your first sandbox. It's as simple as saying "make_sandbox" and the name of a MySQL tarball.
This will expand the tarball and create a sandbox very fast.
If you have already expanded the tarball in a predefined directory, you can call "make_sandbox" with the simplified syntax.
It is FAST!
105. Creating a single
sandbox
•as normal user
!"1%2345%&-./0"6
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
•if you have expanded tarballs already
Let's make your first sandbox. It's as simple as saying "make_sandbox" and the name of a MySQL tarball.
This will expand the tarball and create a sandbox very fast.
If you have already expanded the tarball in a predefined directory, you can call "make_sandbox" with the simplified syntax.
It is FAST!
106. Creating a single
sandbox
•as normal user
!"1%2345%&-./0"6
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
•if you have expanded tarballs already
!"1%2345%&-./0"=>?>@=
Let's make your first sandbox. It's as simple as saying "make_sandbox" and the name of a MySQL tarball.
This will expand the tarball and create a sandbox very fast.
If you have already expanded the tarball in a predefined directory, you can call "make_sandbox" with the simplified syntax.
It is FAST!
107. Creating a single
sandbox
•as normal user
!"1%2345%&-./0"6
< 10 seconds!
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
• if you have expanded tarballs already
!"1%2345%&-./0"=>?>@=
Let's make your first sandbox. It's as simple as saying "make_sandbox" and the name of a MySQL tarball.
This will expand the tarball and create a sandbox very fast.
If you have already expanded the tarball in a predefined directory, you can call "make_sandbox" with the simplified syntax.
It is FAST!
108. Creating a replication
sandbox
•as normal user
!"1%234G3$;H#%8H/&45%&-./0"6
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
Creating a replication system is equally easy. If you have ever set up MySQL replication servers you know that it is not extremely
complicated, but the chances of making mistakes are quite a lot.
Using MySQL Sandbox, you can create a replication system as easoly as you make a single one. And you will be surprised at how
fast it is!
109. Creating a replication
sandbox
•as normal user
!"1%234G3$;H#%8H/&45%&-./0"6
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
•if you have expanded tarballs already
Creating a replication system is equally easy. If you have ever set up MySQL replication servers you know that it is not extremely
complicated, but the chances of making mistakes are quite a lot.
Using MySQL Sandbox, you can create a replication system as easoly as you make a single one. And you will be surprised at how
fast it is!
110. Creating a replication
sandbox
•as normal user
!"1%234G3$;H#%8H/&45%&-./0"6
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
•if you have expanded tarballs already
!"1%234G3$;H#%8H/&45%&-./0"=>?>@=
Creating a replication system is equally easy. If you have ever set up MySQL replication servers you know that it is not extremely
complicated, but the chances of making mistakes are quite a lot.
Using MySQL Sandbox, you can create a replication system as easoly as you make a single one. And you will be surprised at how
fast it is!
111. Creating a replication
sandbox
•as normal user
!"1%234G3$;H#%8H/&45%&-./0"6
< 20 seconds!
"""7$%8978/71(5:;<=>?>@=<ABCDB)>EF
• if you have expanded tarballs already
!"1%234G3$;H#%8H/&45%&-./0"=>?>@=
Creating a replication system is equally easy. If you have ever set up MySQL replication servers you know that it is not extremely
complicated, but the chances of making mistakes are quite a lot.
Using MySQL Sandbox, you can create a replication system as easoly as you make a single one. And you will be surprised at how
fast it is!
112. SHORTCUT - Creating
and Using a sandbox
Starting with MySQL Sandbox 3.0.04, there is also a shortcut script that can make your life much easier.
You can create a sandbox and use it with a very short command.
You need to try it to believe it.
113. SHORTCUT - Creating
and Using a sandbox
•as normal user (requires version 3.0.04)
Starting with MySQL Sandbox 3.0.04, there is also a shortcut script that can make your life much easier.
You can create a sandbox and use it with a very short command.
You need to try it to believe it.
114. SHORTCUT - Creating
and Using a sandbox
•as normal user (requires version 3.0.04)
!"5."=>I>J@
Starting with MySQL Sandbox 3.0.04, there is also a shortcut script that can make your life much easier.
You can create a sandbox and use it with a very short command.
You need to try it to believe it.
115. SHORTCUT - Creating
and Using a sandbox
•as normal user (requires version 3.0.04)
!"5."=>I>J@
< 5 seconds!
Starting with MySQL Sandbox 3.0.04, there is also a shortcut script that can make your life much easier.
You can create a sandbox and use it with a very short command.
You need to try it to believe it.
116. example
K"1%2345%&-./0"=>I>JL"
M>>>N
>"5%&-./0"53GO3G"58%G83-
A/PG"5%&-./0"53GO3G"Q%5"H&58%;;3-"H&"
K)RSTUBV4WB'X715.4=4I4JL
K"K)RSTUBV4WB'X715.4=4I4JL7P53"6
"""<3"Y53;3#8"O3G5H/&Z[Y
<<<<<<<<<<<
]"O3G5H/&Z["]
<<<<<<<<<<<
]"=>I>JL""""]"
<<<<<<<<<<<
Here's an example of a single sandbox. First you create it. MySQL Sandbox will show you what it's doing and ask for
confirmation. This will take a few seconds. Once the sandbox has been created, you can use it immediately. No need to
remember complicated options. The sandbox includes scripts to use it easily, as you see in the screen. Just say "use", and it will
invoke the mysql command line with all the necessary options, which you don't have to remember
117. example
(shortcut)
K"8H13"5."=>I>JL"<3"Y53;3#8"O3G5H/&Z[Y
M>>>N
>"5%&-./0"53GO3G"58%G83-
A/PG"5%&-./0"53GO3G"Q%5"H&58%;;3-"H&"
K)RSTUBV4WB'X715.4=4I4JL
<<<<<<<<<<<
]"O3G5H/&Z["]
<<<<<<<<<<<
]"=>I>JL""""]"
<<<<<<<<<<<
G3%;" I1L>I^?5
P53G" I1I>L_I5
5(5"
I1I>L?I5
The same two tasks that you have seen in the previous slide can be achieved at once with the new shortcut.
One single command that creates the sandbox and lets you use it.
This timing is in my laptop. Using a powerful server will be even faster.
118. example replication
K"1%234G3$;H#%8H/&45%&-./0"=>I>JL"
M>>>N
G3$;H#%8H/&"-HG3#8/G("H&58%;;3-"/&"
K)RSTUBV4WB'X7G5%&-./04=4I4JL
K"K)RSTUBV4WB'X7G5%&-./04=4J4JL71"6
""<3"Y53;3#8"O3G5H/&Z[Y
<<<<<<<<<<<
]"O3G5H/&Z["]
<<<<<<<<<<<
]"=>I>JL""""]"
<<<<<<<<<<<
Creating a replication system is similar. Just use the make_replication_sandbox script instead of make_sandbox, and the program
will take care of all the details.
Inside a replication sandbox you will have one sandbox for the master and one for each slave. No need to remember which is
which. The sandbox o!ers a shortcut script for each role. "m" is for master, "s1" for the first slave, and so on.
119. example replication
(shortcut)
K"8H13"5."G=>I>JL"<3"Y53;3#8"O3G5H/&Z[Y
M>>>N
G3$;H#%8H/&"-HG3#8/G("H&58%;;3-"H&"KWB'X7
G5%&-./04=4I4JL
<<<<<<<<<<<<
]"O3G5H/&Z[""]
<<<<<<<<<<<<
]"=>I>JL<;/E"]"
<<<<<<<<<<<<
G3%;" I1^>`JL5
P53G" I1I>a_=5
5(5"
I1I>=J=5
You can use the shortcut script for the replication as well.
Here's an example of such call. You will invoke sb, followed by an "r" and the version number. The shortcut script will do
everything for you. Create a replication system and then invoke the master.
120. more control with
replication
K"#-"K)RSTUBV4WB'X7G5%&-./04=4J4JL
K">7P534%;;"Y)X+Xbc"dd53GO3G4H-Y
!"1%583G""
dd53GO3G4H-
?
!"53GO3G,"?,"
dd53GO3G4H-
?I?
!"53GO3G,"L,"
dd53GO3G4H-
?IL
For multiple sandboxes, you have additional scripts. There are scripts for starting, stopping, and cleaning up all the depending
sandboxes at once. And there is a script that lets you tun the same SQL statement in all the nodes. In this example, you see the
query "SELECT @@server_id" executed by the master and the slaves in sequence.
121. Self contained
•All sandboxes are created inside
$SANDBOX_HOME
•Use all at once
•Great control
http://mysqlsandbox.net
Using MySQL Sandbox servers is safe and easy. Stopping and starting all the servers at once is a simple script call. Since all
sandboxes are under the same tree, it's also easy to keep track of storage.
There is much more that you can do. Check the MySQL Sandbox site for the reference manual and a detailed cookbook with
practical guidance.
122. Pasos para no morir
de éxito:
•Optimizar la aplicación
•Optimizar la base de datos
•Escalar fácilmente
A modo de resúmen, unos pasos para mejorar el rendimiento en una aplicación.
123. ¡Gracias!
No Mueras de Éxito
Víctor Jiménez <vjimenez@warp.es>
Giuseppe Maxia <datacharmer@sun.com>
http://mysql.com/products/enterprise
http://mysqlsandbox.net
http://mysql.com/training
http://www.warp.es
The Chicken and the monkey are licensed under Public Domain, find them in:
http://openclipart.org/media/people/johnny_automatic
Muchas gracias, podéis encontrar más información en...
Este tema está tratado más en profundidad en los cursos de PT y HA...