<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Geronimo Velasco on Medium]]></title>
        <description><![CDATA[Stories by Geronimo Velasco on Medium]]></description>
        <link>https://medium.com/@geronimovelasco?source=rss-f26913ebede0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NkEqu2S6tv3my6qZ0sOj4A.jpeg</url>
            <title>Stories by Geronimo Velasco on Medium</title>
            <link>https://medium.com/@geronimovelasco?source=rss-f26913ebede0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:17:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@geronimovelasco/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Think About B-tree Indexes in PostgreSQL]]></title>
            <link>https://geronimovelasco.medium.com/how-i-think-about-b-tree-indexes-in-postgresql-a9e04b84d8d1?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e04b84d8d1</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 23:13:37 GMT</pubDate>
            <atom:updated>2026-06-12T23:13:37.040Z</atom:updated>
            <content:encoded><![CDATA[<p>B-tree indexes are a very special data structure because they allow efficient searches in tables with millions of rows. However, we can go beyond the usual explanation and look at a practical implementation example: what the “pointer” actually is, what it contains, and how it gives us a clearer picture than the simple phrase “the index has a pointer to the table.”</p><p>There is the classic book analogy: in a book, by looking at the index, you can jump directly to the page or pages where the information you need is located. I like that analogy, but I want to emphasize something: an index is not meant to deal with millions of rows. It is actually the opposite. The purpose of an index is to avoid dealing with millions of rows by acting as a fast path to the information.</p><p>Ask yourself this: what is the best way to work with a table that has billions of rows?</p><p>Think about it…</p><p>You will probably think of sharding, partitioning, read replicas, indexes, and other techniques. All of those techniques naturally answer the question. The best way to work with a table that has billions of rows is precisely to avoid working with a table that has billions of rows.</p><h3>Recap</h3><p>Before getting into the main topic, I would like to briefly review some PostgreSQL concepts that I consider important.</p><h3>Page Format</h3><p>Each table is logically divided into pages. In PostgreSQL, the default page size is 8 KB. A page acts as the minimum read unit: PostgreSQL does not read less than one page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*rooXURJU-Nsh2DdWkuPjpw.png" /><figcaption><em>Super simplified table example</em></figcaption></figure><h3>Page Structure</h3><p>Internally, a page is divided into several areas, but I want to highlight the following three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3-jbkalJhaPMYU14aZNCQ.png" /><figcaption>Page Structure</figcaption></figure><h3>1. Header — PageHeaderData</h3><p>As with everything in life, there is a header that contains general information about the page, such as where there is free space for new tuples and the size of the page itself.</p><h3>2. Item Pointer Array — ItemIdData</h3><p>This is an array that works like a table of contents. Inside it, we find the byte offset and the length of each tuple, or row, within the page. This allows us to know the exact location of a tuple and its length.</p><h3>3. Items — the rows themselves</h3><p>This is where the actual row data lives.</p><h3>CTID</h3><p>The CTID is the physical identifier of a tuple, the famous “pointer.” It is formed by the pair:</p><pre>(page_number, item_pointer_array_index)</pre><p>This column exists by default in any table we create.</p><pre>postgres=# SELECT ctid, * FROM customers LIMIT 10;<br>  ctid  |   id    | last_name<br>--------+---------+-----------<br> (0,1)  | 4000001 | Rodriguez<br> (0,2)  | 4000002 | Miller<br> (0,3)  | 4000003 | Miller<br> (0,4)  | 4000004 | Rodriguez<br> (0,5)  | 4000005 | Davis<br> (0,6)  | 4000006 | Brown<br> (0,7)  | 4000007 | Davis<br> (0,8)  | 4000008 | Johnson<br> (0,9)  | 4000009 | Williams<br> (0,10) | 4000010 | Rodriguez<br>(10 rows)</pre><p>When we create an index, the reference or pointer used by the index is, in fact, the CTID.</p><p>This way, PostgreSQL can locate the row directly without doing a sequential scan page by page and row by row. With the CTID, PostgreSQL knows the page number, and since the page size is fixed by default at 8 KB, it can jump directly to that page. Then, using the other part of the CTID, which contains the index inside the item pointer array, PostgreSQL can know the exact byte offset where the tuple is located inside the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBnKIXlp10inopBNVEPlcQ.png" /><figcaption><em>Direct access to a tuple through CTID and offset from the page pointer array.</em></figcaption></figure><h3>Lab</h3><p>For this lab, we have a customers table with two columns: id and last_name. Both have indexes.</p><pre>postgres=# \dt customers<br>           List of relations<br> Schema |   Name    | Type  |  Owner<br>--------+-----------+-------+----------<br> public | customers | table | postgres<br>(1 row)</pre><pre>postgres=# \d customers<br>                             Table &quot;public.customers&quot;<br> Column    |  Type   | Collation | Nullable |               Default               <br>-----------+---------+-----------+----------+-------------------------------------<br> id        | integer |           | not null | nextval(&#39;customers_id_seq&#39;::regclass)<br> last_name | text    |           |          | <br>Indexes:<br>    &quot;customers_pkey&quot;          PRIMARY KEY, btree (id)<br>    &quot;customers_last_name_idx&quot; btree (last_name)</pre><p>To simulate an Index Scan, I will use the pageinspect extension, which lets us inspect PostgreSQL index pages internally. I also have a function called data_to_text() that converts the index value into readable text.</p><p>The table contains around 2 million rows. Let’s see what plan PostgreSQL chooses for the following query. I will use LIMIT 1 because the index contains duplicate values, and this will help us later when we observe deduplication behavior.</p><pre>postgres=# EXPLAIN ANALYZE<br>SELECT ctid, *<br>  FROM customers<br> WHERE last_name = &#39;Brow&#39;<br> LIMIT 1;</pre><pre>QUERY PLAN<br>--------------------------------------------------------------------------------------------<br> Limit  (cost=0.43..8.41 rows=1 width=17) (actual time=0.043..0.044 rows=1 loops=1)<br>   -&gt;  Index Scan using customers_last_name_idx on customers<br>         (cost=0.43..8.41 rows=1 width=17) (actual time=0.042..0.042 rows=1 loops=1)<br>         Index Cond: (last_name = &#39;Brow&#39;::text)<br> Planning Time: 0.196 ms<br> Execution Time: 0.076 ms<br>(5 rows)</pre><p>We can see that PostgreSQL uses the index with the condition, and it returns the following result:</p><pre>postgres=# SELECT ctid,* FROM customers WHERE last_name = &#39;Brow&#39; LIMIT 1;<br>    ctid     |   id    | last_name<br>-------------+---------+-----------<br> (10810,151) | 6000001 | Brow<br>(1 row)</pre><p>Now, let’s imagine we are looking for the value Smith.</p><p>Although I did not mention it before, every B-tree index has a metapage. This metapage tells us the starting page, the root page, and the number of tree levels.</p><pre>postgres=# SELECT root, level FROM bt_metap(&#39;customers_last_name_idx&#39;);<br> root | level<br>------+-------<br>  209 |     2<br>(1 row)</pre><p>Here, the root value tells us the page number where the index starts.</p><p>The level value tells us the number of levels above the leaf pages. In other words, this index has 3 levels in total: root, intermediate nodes, and leaf nodes.</p><p>Let’s inspect the content of root page 209 in the index:</p><pre>SELECT<br>    itemoffset,<br>    ctid,<br>    data_to_text(data) AS last_name,<br>    htid,<br>    tids<br>FROM bt_page_items(&#39;customers_last_name_idx&#39;, 209)<br>ORDER BY itemoffset;</pre><pre>+------------+-------------+-----------+------------+------+<br>| itemoffset | ctid        | last_name | htid       | tids |<br>+------------+-------------+-----------+------------+------+<br>| 1          | (3,0)       |           |            |      |<br>| 2          | (208,4097)  | Davis     | (2248,58)  |      |<br>| 3          | (413,4097)  | Garcia    | (4426,28)  |      |<br>| 4          | (617,4097)  | Johnson   | (6644,160) |      |<br>| 5          | (821,4097)  | Jones     | (8862,157) |      |<br>| 6          | (987,4097)  | Martinez  | (8558,97)  |      |<br>| 7          | (1181,4097) | Miller    | (10097,97) |      |<br>| 8          | (1343,4097) | Rodriguez | (9504,104) |      |<br>| 9          | (1540,4097) | Williams  | (396,43)   |      |<br>| 10         | (1699,4097) | Williams  | (10376,63) |      |<br>+------------+-------------+-----------+------------+------+</pre><p>Here, the CTIDs point to index pages. The first entry does not have a value. Since we are looking for Smith, we should choose entry 8 because:</p><pre>Rodriguez ≤ Smith &lt; Williams</pre><p>So we descend into index page 1343.</p><pre>SELECT<br>    itemoffset,<br>    ctid,<br>    data_to_text(data) AS last_name,<br>    htid,<br>    tids<br>FROM bt_page_items(&#39;customers_last_name_idx&#39;, 1343)<br>ORDER BY itemoffset;</pre><pre>+------------+-------------+-----------+-------------+------+<br>| itemoffset | ctid        | last_name | htid        | tids |<br>+------------+-------------+-----------+-------------+------+<br>| 1          | (1537,4097) | Williams  | (396,43)    |      |<br>| 2          | (1340,0)    |           |             |      |<br>| 3          | (1341,4097) | Rodriguez | (9567,106)  |      |<br>                         ......<br>| 23         | (1362,4097) | Smith     | (7,142)     |      |<br>| 24         | (1363,4097) | Smith     | (69,73)     |      |<br>| 25         | (1364,4097) | Smith     | (132,136)   |      |<br>| 26         | (1365,4097) | Smith     | (196,46)    |      |<br>                         ......<br>+------------+-------------+-----------+-------------+------+</pre><p>As we can see, we found an entry with Smith, but we are still at level 2. That means the CTID still points to an index page. However, we can also check the htid column, which points to the tuple in the table.</p><pre>postgres=# SELECT *<br>             FROM customers<br>            WHERE ctid = &#39;(7,142)&#39;;</pre><pre>+---------+------------+<br>| id      | last_name  |<br>+---------+------------+<br>| 4001437 | Smith      |<br>+---------+------------+<br>(1 row)</pre><p>Although this index contains duplicates in the leaf pages, the third and final level, we can see how PostgreSQL applies deduplication in the tids column. That column contains all the entries that match the indexed value Smith.</p><p>To see this, using entry 23, we go to index page 1362.</p><pre>postgres=# SELECT<br>    itemoffset,<br>    ctid,<br>    data_to_text(data) AS last_name,<br>    htid,<br>    tids<br>FROM bt_page_items(&#39;customers_last_name_idx&#39;, 1362)<br>ORDER BY itemoffset<br>LIMIT 2;</pre><pre>+------------+-----------+-----------+---------+----------------------------------+<br>| itemoffset | ctid      | last_name | htid    | tids                             |<br>+------------+-----------+-----------+---------+----------------------------------+<br>| 1          | (16,4097) | Smith     | (69,73) |                                  |<br>| 2          | (16,8324) | Smith     | (7,145) | {&quot;(7,145)&quot;,&quot;(7,175)&quot;,…,&quot;(14,9)&quot;} |<br>+------------+-----------+-----------+---------+----------------------------------+<br>(2 rows)</pre><p>Now we can see that the tids column is no longer empty. It contains a list of CTIDs that satisfy the condition of having the value Smith. This lets us clearly observe deduplication.</p><p>If we search for any of those CTIDs:</p><pre>postgres=# SELECT *<br>             FROM customers<br>            WHERE ctid = &#39;(14,9)&#39;;</pre><pre>+---------+-----------+<br>| id      | last_name |<br>+---------+-----------+<br>| 4002599 | Smith     |<br>+---------+-----------+<br>(1 row)</pre><p>And that is the end of our artificial index scan — haha!</p><p>Now we have a clearer picture of what happens when PostgreSQL decides to use an index. We can also ask ourselves: if I am only searching by last_name, and that value already exists inside the index, do I really need to visit the table?</p><p>The answer is no. That is called an <strong>index-only scan.</strong></p><p>We also saw how deduplication helps save space inside the index.</p><p>Note: unique indexes can also contain duplicates because of MVCC. The deduplication behavior in tids follows the same idea.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e04b84d8d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[¿Cuántas páginas tiene mi tabla en PostgreSQL?]]></title>
            <link>https://geronimovelasco.medium.com/cu%C3%A1ntas-p%C3%A1ginas-tiene-mi-tabla-en-postgresql-538b4c9a9711?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/538b4c9a9711</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 19:20:48 GMT</pubDate>
            <atom:updated>2026-03-02T19:22:41.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*AW9EvvkfQEHrNfVy.png" /></figure><p>Tuve la curiosidad de ver cuántas páginas tiene una de las tablas transaccionales en nuestra base de datos transaccional PostgreSQL.</p><p><strong>Página en PostgreSQL:</strong> una tabla en Postgres está dividida lógicamente en páginas; el término <em>página</em> puede sonar un poco ambiguo, pero puedes pensar en ella como la unidad mínima de lectura que Postgres puede leer desde disco. Postgres no puede leer menos datos que el tamaño de una página.</p><p>El tamaño de página por defecto en Postgres es 8k. Puedes usar la siguiente consulta para ver el tamaño de página:</p><pre>db=# SHOW block_size;<br><br> block_size<br>------------<br> 8192<br>(1 row)</pre><p>Para saber cuántas páginas tiene una tabla, necesitamos obtener el tamaño de la tabla en bytes y luego dividirlo por el tamaño de la página para ver cuántas páginas tiene realmente.</p><pre>db=# select pg_relation_size(&#39;transactions&#39;) as bytes,<br> pg_relation_size(&#39;transactions&#39;) / 8192 as pages;<br><br>     bytes     |    pages<br>---------------+--------------<br> 4,872,519,680 |    594,790</pre><p>Para consultar una fila de una página específica, podemos usar el CTID.</p><p>El CTID no es más que la ubicación física de una fila; nos dice dónde está esa fila en el heap.</p><pre>db=# select ctid, id from app_user;<br> ctid  |                  id<br>-------+--------------------------------------<br> (0,5) | 2ef257c9-bec7-4294-83d1-d695e9b93e08<br> (0,6) | 09b1fcb8-b6b5-4889-ad49-159fad617a81<br>(2 rows)</pre><p>El CTID está compuesto por dos valores:</p><p>(numero_pagina, index_item_pointer_array)</p><p>Entonces, para el CTID (0,5):<br>0 representa el número de página.<br>5 representa el índice del arreglo de punteros de ítems para esa fila, pero puedes pensarlo como la posición de la tupla dentro de la página.</p><p>De hecho, podemos consultar el CTID (0,5):</p><pre>db=# select ctid, id from app_user where ctid = &#39;(0,5)&#39;;<br> ctid  |                  id<br>-------+--------------------------------------<br> (0,5) | 2ef257c9-bec7-4294-83d1-d695e9b93e08<br>(1 row)</pre><p>El número de página más alto de CTID que encontré con tuplas vivas fue alrededor de 380k. ¿Por qué?</p><p>Esperaba que la página más alta referenciada por CTID estuviera cerca del número de páginas retornado por pg_relation_size, pero era mucho menor.</p><p>Mi intuición es que, como esta es una tabla transactions con muchas actualizaciones, la diferencia puede estar relacionada con cómo Postgres maneja internamente los updates. Vimos que la tabla tiene alrededor de 594,790 páginas, pero eso no significa que todas estén llenas de tuplas. No podemos asumir que todo el espacio asignado esté siendo usado actualmente por tuplas vivas.</p><p>Creo que esto tiene que ver con vacuum y con las dead tuples, porque las filas en Postgres son inmutables. Si actualizamos una fila, en realidad estamos creando una nueva versión de ella. Así que, aunque lógicamente pensemos en ella como una sola fila, físicamente puede haber múltiples versiones de esa misma fila.</p><p>Eso es parte del mecanismo MVCC de PostgreSQL.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=538b4c9a9711" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Many Pages Does My PostgreSQL Table Have?]]></title>
            <link>https://geronimovelasco.medium.com/how-many-pages-does-my-postgresql-table-have-59514010e62c?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/59514010e62c</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 19:14:59 GMT</pubDate>
            <atom:updated>2026-03-02T19:14:59.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*JGuUjez4yEvQaVck.png" /></figure><p>I had the curiosity to see how many pages one of the transactional tables has in our PostgreSQL transactional database.</p><p>PostgreSQL Page: A table in Postgres is divided logically into pages; the term page can sound a little bit ambiguous, but think of it as the minimal read unit Postgres can read from disk. Postgres cannot read less data than the page size.</p><p>The default page size in Postgres is 8k. You can use the following query to see the page size:</p><pre>db=# SHOW block_size;<br><br> block_size<br>------------<br> 8192<br>(1 row)</pre><p>To know how many pages a table has, we need to get the size in bytes of the table and then divide it by the page size to see how many pages it actually has.</p><pre>db=# select pg_relation_size(&#39;transactions&#39;) as bytes,<br> pg_relation_size(&#39;transactions&#39;) / 8192 as pages;<br><br>     bytes     |    pages<br>---------------+--------------<br> 4,872,519,680 |    594,790<br></pre><p>To query a row from a specific page, we can use the CTID.</p><p>The CTID is nothing but the physical location of a row; it tells us where that row is in the heap.</p><pre>db=# select ctid, id from app_user;<br> ctid  |                  id<br>-------+--------------------------------------<br> (0,5) | 2ef257c9-bec7-4294-83d1-d695e9b93e08<br> (0,6) | 09b1fcb8-b6b5-4889-ad49-159fad617a81<br>(2 rows)</pre><p>CTID is composed of two values: (page_number, index_item_pointer_array)</p><p>So for CTID (0,5):<br>0 represents the page number<br>5 represents the index of the item’s pointer array for that row, but you can think of it as the position of the tuple within the page.</p><p>We can actually query the CTID (0,5):</p><pre>db=# select ctid, id from app_user where ctid = &#39;(0,5)&#39;;<br> ctid  |                  id<br>-------+--------------------------------------<br> (0,5) | 2ef257c9-bec7-4294-83d1-d695e9b93e08<br>(1 row)</pre><p>The highest CTID page number I found with live tuples was around 380k. Why?</p><p>I expected the highest page referenced by CTID to be close to the page count returned by `pg_relation_size`, but it was much lower.</p><p>My intuition is that, since this is a heavily updated `transactions` table, the difference may be related to how Postgres handles updates internally. We saw that the table has around 594,790 pages, but that does not mean all of them are full of tuples. We cannot assume all the allocated space is currently used by live tuples.</p><p>I think this has something to do with vacuum and dead tuples, because rows in Postgres are immutable. If we update a row, we are actually creating a new version of it. So even if, logically, we think about it as one row, physically there can be multiple versions of that same row.</p><p>That is part of PostgreSQL’s MVCC mechanism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59514010e62c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como veo los indices Btree en PostgreSQL]]></title>
            <link>https://geronimovelasco.medium.com/como-veo-los-indices-btree-en-postgresql-2eb474c5ff42?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb474c5ff42</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Tue, 13 May 2025 15:23:39 GMT</pubDate>
            <atom:updated>2025-05-13T15:23:39.180Z</atom:updated>
            <content:encoded><![CDATA[<p>Los índices B-tree son una estructura de datos esotérica y muy especial, ya qué permite búsquedas eficientes en tablas con millones de registros. Sin embargo podemos ver un ejemplo de implementación y ver como es el ‘puntero’ realmente, que contiene y tener un imagen más clara que la simple frase de que el índice tiene un puntero hacía la tabla.</p><p>Esta el clásico ejemplo del libro: En un libro, con solo ver el índice puedes saltar directamente a la página o páginas que necesites para encontrar la información. Me gusta, pero quisiera hacer énfasis en que un índice no es para tratar con millones de registros, sino exactamente lo contrario: el propósito del índice es evitar tratar con millones de registros, funcionando como una ruta rápida hacia la información.</p><p>Pregúntate lo siguiente: ¿Cuál es la mejor forma de tratar con una tabla de miles de millones de registros? Piénsalo… probablemente se te venga a la mente sharding, particiones, réplicas de solo lectura, índices y otras técnicas. Todas esas técnicas, de manera innata, responden la pregunta. La mejor manera de trabajar con una tabla de miles de millones de registros es precisamente evitar trabajar con una tabla con miles de millones de registros</p><p><strong>Recapitulación</strong><br> Antes de entrar en materia, me gustaría repasar brevemente algunas características que considero importantes de Postgres.</p><p><strong>Formato de página</strong><br> Cada tabla se divide de manera lógica en páginas; en Postgres el tamaño por defecto es de 8 KB. La página actúa como la unidad mínima de lectura: Postgres no lee menos de una página.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*rooXURJU-Nsh2DdWkuPjpw.png" /><figcaption>Ejemplo de tabla super simplificado</figcaption></figure><p><strong>Estructura de una página</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3-jbkalJhaPMYU14aZNCQ.png" /><figcaption>Áreas de una página</figcaption></figure><p>Internamente, una página está dividida en varias áreas, pero quisiera resaltar las siguientes tres:</p><ol><li><strong>Header (PageHeaderData)</strong><br> Como todo en la vida, hay un header que contiene la información general de la página, por ejemplo dónde hay espacio libre para nuevas tuplas y el tamaño de la misma.</li><li><strong>Item pointer array (ItemIdData)</strong><br> Es un array que sirve como tabla de contenido; dentro encontramos el<em> offset en bytes </em>y la longitud de cada tupla (registro) en la página. nos permite saber la ubicación exacta de una tupla y su longitud.</li><li><strong>Items (los registros en sí)</strong><br>Aquí reside la información de las filas.</li></ol><p><strong>CTID</strong><br> Es el identificador físico de la tupla, el famoso “puntero” formado por el par (número_de_página, índice_del_item_pointer_array). Esta columna viene por defecto en cualquier tabla que creemos.</p><pre>postgres=# SELECT ctid, * FROM customers LIMIT 10;<br>  ctid  |   id    | last_name<br>--------+---------+-----------<br> (0,1)  | 4000001 | Rodriguez<br> (0,2)  | 4000002 | Miller<br> (0,3)  | 4000003 | Miller<br> (0,4)  | 4000004 | Rodriguez<br> (0,5)  | 4000005 | Davis<br> (0,6)  | 4000006 | Brown<br> (0,7)  | 4000007 | Davis<br> (0,8)  | 4000008 | Johnson<br> (0,9)  | 4000009 | Williams<br> (0,10) | 4000010 | Rodriguez<br>(10 rows)</pre><p>Cuando creamos un <strong>índice</strong>, la referencia o puntero que usa el índice es, en efecto, el <strong>CTID</strong>.</p><p>De este modo, Postgres es capaz de ubicar directamente el registro sin necesidad de hacer un escaneo secuencial página por página y registro por registro, sino que, con el <strong>CTID</strong>, ubica el número de la página y, dado que el tamaño de la página es fijo (por defecto 8 KB), podemos saltar directamente allí; luego, con la otra mitad del <strong>CTID </strong>que contiene el índice en el <em>array of item pointers</em>, podemos saber el <em>offset en bytes</em> exacto donde se encuentra la tupla dentro de la página.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cMlPcVHVffUj-CvHmKzGg.png" /><figcaption>Acceso directo a tupla vía CTID (verde) y offset (rojo) desde el array de punteros de página</figcaption></figure><h4><strong>Laboratorio</strong></h4><p>Para el laboratorio, tenemos la siguiente tabla <strong>customers</strong> con dos columnas: <strong>id</strong> y <strong>last_name</strong>. Ambos con índice.</p><pre>postgres=# \dt customers<br>           List of relations<br> Schema |   Name    | Type  |  Owner   <br>--------+-----------+-------+----------<br> public | customers | table | postgres<br>(1 row)<br><br>postgres=# \d customers<br>                             Table &quot;public.customers&quot;<br> Column    |  Type   | Collation | Nullable |               Default               <br>-----------+---------+-----------+----------+-------------------------------------<br> id        | integer |           | not null | nextval(&#39;customers_id_seq&#39;::regclass)<br> last_name | text    |           |          | <br>Indexes:<br>    &quot;customers_pkey&quot;          PRIMARY KEY, btree (id)<br>    &quot;customers_last_name_idx&quot; btree (last_name)</pre><p>Para simular un <strong>Index Scan</strong>, usaré la extensión pageinspect, que permite ver internamente las páginas de índice en Postgres. Además, tengo una función (data_to_text()) que convierte el valor del índice en un texto legible.</p><p>La tabla contiene alrededor de 2 millones de registros. Veamos qué plan elige Postgres para la siguiente consulta (con LIMIT 1 porque el índice tendrá duplicados, y así luego podemos observar el comportamiento de la deduplicación):</p><pre>postgres=# EXPLAIN ANALYZE<br>SELECT ctid, *<br>  FROM customers<br> WHERE last_name = &#39;Brow&#39;<br> LIMIT 1;<br><br>                                     QUERY PLAN<br>--------------------------------------------------------------------------------------------<br> Limit  (cost=0.43..8.41 rows=1 width=17) (actual time=0.043..0.044 rows=1 loops=1)<br>   -&gt;  Index Scan using customers_last_name_idx on customers<br>         (cost=0.43..8.41 rows=1 width=17) (actual time=0.042..0.042 rows=1 loops=1)<br>         Index Cond: (last_name = &#39;Brow&#39;::text)<br> Planning Time: 0.196 ms<br> Execution Time: 0.076 ms<br>(5 rows)</pre><p>Vemos que usa el índice con la condición, y nos devuelve el siguiente resultado:</p><pre>postgres=# SELECT ctid,* FROM customers WHERE last_name = &#39;Brow&#39; LIMIT 1;<br>    ctid     |   id    | last_name<br>-------------+---------+-----------<br> (10810,151) | 6000001 | Brow<br>(1 row)</pre><p>Imaginemos que estamos buscando el valor <strong>Smith</strong>:</p><p>Aunque no lo mencioné antes, todo índice B-tree tiene una <strong>metapage</strong>, que nos indica la página inicial (la raíz) y los niveles del árbol:</p><pre>postgres=# SELECT root, level FROM bt_metap(&#39;customers_last_name_idx&#39;);<br> root | level<br>------+-------<br>  209 |     2<br>(1 row)</pre><p>Aquí, el valor root nos indica el número de la página del índice donde comienza el índice.</p><p>Level nos indica el número de niveles por encima de las leaf pages; básicamente nos dice que el índice tiene 3 niveles en total: raíz, nodos intermedios y leaf nodes.</p><p>Veamos el contenido de la <strong>página raíz 209</strong> del índice:</p><pre>postgres=# SELECT<br>               itemoffset,<br>               ctid,<br>               data_to_text(data) AS last_name,<br>               htid,<br>               tids<br>           FROM bt_page_items(&#39;customers_last_name_idx&#39;, 209)<br>           ORDER BY itemoffset;<br><br>+------------+-------------+-----------+------------+------+<br>| itemoffset | ctid        | last_name | htid       | tids |<br>+------------+-------------+-----------+------------+------+<br>| 1          | (3,0)       |           |            |      |<br>| 2          | (208,4097)  | Davis     | (2248,58)  |      |<br>| 3          | (413,4097)  | Garcia    | (4426,28)  |      |<br>| 4          | (617,4097)  | Johnson   | (6644,160) |      |<br>| 5          | (821,4097)  | Jones     | (8862,157) |      |<br>| 6          | (987,4097)  | Martinez  | (8558,97)  |      |<br>| 7          | (1181,4097) | Miller    | (10097,97) |      |<br>| 8          | (1343,4097) | Rodriguez | (9504,104) |      |<br>| 9          | (1540,4097) | Williams  | (396,43)   |      |<br>| 10         | (1699,4097) | Williams  | (10376,63) |      |<br>+------------+-------------+-----------+------------+------+</pre><p>Aquí los <strong>CTID</strong> apuntan a páginas de índice. La primera entrada no tiene ninguno. Como estamos buscando ‘Smith’, debemos escoger el registro 8, dado que<br> Rodriguez ≤ Smith &lt; Williams,<br> y descender a la <strong>página 1343 del índice</strong>:</p><pre>SELECT<br>    itemoffset,<br>    ctid,<br>    data_to_text(data)  AS last_name,<br>    htid,<br>    tids<br>FROM<br>    bt_page_items(&#39;customers_last_name_idx&#39;, 1343)<br>ORDER BY<br>    itemoffset;<br><br>+------------+-------------+-----------+-------------+------+<br>| itemoffset | ctid        | last_name | htid        | tids |<br>+------------+-------------+-----------+-------------+------+<br>| 1          | (1537,4097) | Williams  | (396,43)    |      |<br>| 2          | (1340,0)    |           |             |      |<br>| 3          | (1341,4097) | Rodriguez | (9567,106)  |      |<br>                        ......<br>| 23         | (1362,4097) | Smith     | (7,142)     |      |<br>| 24         | (1363,4097) | Smith     | (69,73)     |      |<br>| 25         | (1364,4097) | Smith     | (132,136)   |      |<br>| 26         | (1365,4097) | Smith     | (196,46)    |      |<br>                         ......<br>+------------+-------------+-----------+-------------+------+</pre><p>Como vemos, encontramos una entrada con <strong>Smith</strong>, pero seguimos en el nivel 2, por lo que el CTID sigue apuntando a una página de índice, aunque podemos consultar la columna <strong>htid</strong>, que apunta a la tupla en la tabla.</p><pre>postgres=# SELECT *<br>             FROM customers<br>           WHERE ctid = &#39;(7,142)&#39;;<br><br><br>+---------+------------+<br>| id      | last_name  |<br>+---------+------------+<br>| 4001437 | Smith      |<br>+---------+------------+<br>(1 row)</pre><p>Aunque este índice tiene duplicados en las leaf pages (3rd y último nivel), podemos ver cómo Postgres aplica deduplicación en la columna <strong>tids</strong>: allí aparecen todas las entradas que cumplen con el índice <strong>Smith</strong>. Para ello, con el registro <strong>23</strong>, vamos a la <strong>página de índice 1362</strong>:</p><pre>postgres=# SELECT<br>    itemoffset,<br>    ctid,<br>    data_to_text(data)    AS last_name,<br>    htid,<br>    tids<br>FROM<br>    bt_page_items(&#39;customers_last_name_idx&#39;, 1362)<br>ORDER BY<br>    itemoffset<br>LIMIT 2;<br><br>+------------+-------------+-----------+------------+-----------------------------+<br>| itemoffset | ctid      | last_name | htid    | tids                             |<br>+------------+-----------+-----------+---------+----------------------------------+<br>| 1          | (16,4097) | Smith     | (69,73) |                                  |<br>| 2          | (16,8324) | Smith     | (7,145) | {&quot;(7,145)&quot;,&quot;(7,175)&quot;,…,&quot;(14,9)&quot;} |<br>+------------+-------------+-----------+-------------+----------------------------+<br>(2 rows)</pre><p>Vemos que la columna <strong>tids</strong> ya no está vacía y contiene una lista de <strong>CTID</strong>s que cumplen la condición de tener el valor <strong>Smith</strong>, por lo que podemos apreciar la deduplicación. Si buscamos cualquiera de esos CTIDs:</p><pre>postgres=# SELECT *<br>              FROM customers<br>              WHERE ctid = &#39;(14,9)&#39;;<br><br>+---------+-----------+<br>| id      | last_name |<br>+---------+-----------+<br>| 4002599 | Smith     |<br>+---------+-----------+<br>(1 row)</pre><p>Con esto acabamos nuestro index scan artificial, ¡haha! Ya tenemos una imagen más clara de lo que ocurre cuando Postgres decide usar un índice y podemos preguntarnos: si solo busco por el <strong>last_name</strong>, en realidad eso ya está dentro del índice, por lo que no necesito ir a consultar la tabla. A esto se le llama <strong>index-only scan</strong>. También vimos la deduplicación para ahorrar espacio dentro del índice.</p><p><strong>Nota:</strong> Los índices únicos también pueden tener duplicados (por razones del MVCC), el comportamiento de deduplicación en lostids es el mismo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb474c5ff42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How LIMIT and OFFSET works behind the Scenes in PostgreSQL]]></title>
            <link>https://geronimovelasco.medium.com/how-limit-and-offset-works-behind-the-scenes-in-postgresql-a09c2c063405?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a09c2c063405</guid>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 22:50:24 GMT</pubDate>
            <atom:updated>2024-01-03T16:31:15.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdTN7AprzuJYfP4f5O7Osw.jpeg" /></figure><p>When we talk about pagination, what is the first approach that comes to your mind? In my case, I immediately think of <strong>‘LIMIT’ </strong>and <strong>‘OFFSET’,</strong> so I use them. Is it good, right? Well, in my case, I realized it was inefficient for large paginations.</p><p>Let’s delve a bit deeper into this.</p><h3>1. Setup</h3><p>I’ve created a simple demo with a <strong>‘users’</strong> table populated with 10 million rows.</p><pre>-- Create the user table<br>CREATE TABLE users (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(100),<br>    gender VARCHAR(10)<br>);<br><br>-- Generate and insert 10 million rows using generate_series<br>INSERT INTO users (name, gender)<br>SELECT<br>    &#39;User &#39; || gs.num AS name,<br>    CASE WHEN gs.num % 2 = 0 THEN &#39;Male&#39; ELSE &#39;Female&#39; END AS gender<br>FROM generate_series(1, 10000000) AS gs(num);</pre><h3>2. SQL LIMIT and OFFSET</h3><p><strong>LIMIT </strong>and <strong>OFFSET </strong>allows you to retrieve a subset of rows of the query.<br><br>Let’s write the SQL query for pagination.</p><pre>    SELECT * FROM users ORDER BY id LIMIT 500 OFFSET 1000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*r5Qy8JMeBjdD8khEb2xKNg.png" /></figure><p>For me, this looks like magic. How does Postgres know how to skip those records? Well, it actually doesn’t know how to skip those records.</p><p>Let’s analyze the SQL query with the <strong>‘EXPLAIN ANALYZE’</strong> command.</p><pre>EXPLAIN ANALYZE SELECT * FROM users ORDER BY id LIMIT 500 OFFSET 1000;</pre><p>After executing the SQL query, we obtained the query plan and execution statistics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*f6a4FwDGUR1veyBsU4lRLQ.png" /></figure><p>Let’s dive into the query plan in more detail.</p><p>The query plan consists of two parts:</p><p>Firstly, we notice that Postgres chooses an Index Scan on the primary key as we’re ordering the results based on the ‘id’ using the <strong>ORDER BY</strong> clause. Secondly, Postgres then limits the results to return the required rows.</p><p>If we examine the actual time and rows fetched by Postgres, we can see that it’s actually 1500 instead of 500.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*6DAe_gpQcM05XKoulhXP2A.png" /></figure><p>This means that using LIMIT and OFFSET doesn’t skip the records, it fetches all the records into memory and relies on Postgres to filter them.</p><p>If we refer to the PostgreSQL documentation, we find that this is indeed the case. ‘The rows skipped by an OFFSET clause still have to be computed inside the server; therefore, a large OFFSET might be inefficient’.</p><p>We can say that LIMIT and OFFSET perform well with small offsets, for larger offsets, is there a better approach?</p><h3>3. Is there a better approach for a large OFFSET?</h3><p>We can take advantage of the sequential ID to obtain the same result with more efficiency.</p><pre>SELECT * FROM users WHERE id between 1001 and 1500;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*XyH11i7yytoRe_6D8MLptw.png" /></figure><p>Let’s analyze the query</p><pre>EXPLAIN ANALYZE SELECT * FROM users WHERE id between 1001 and 1500;</pre><p>After executing the query, we can see that it retrieves only the required 500 rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*sJ4MB7S2TyBqDWioM7IxsQ.png" /></figure><h3>4. Conclusion</h3><p>We can conclude that while using LIMIT and OFFSET for pagination can work well for small offsets, for larger offsets, it might be inefficient since it has to pull that in memory and filter the rows. There are other ways to achieve the same result. Taking advantage of ordered columns and indexes could be a better approach for larger offsets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a09c2c063405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cómo funcionan LIMIT y OFFSET de fondo en PostgreSQL]]></title>
            <link>https://geronimovelasco.medium.com/c%C3%B3mo-funcionan-limit-y-offset-de-fondo-en-postgresql-1c65cfd3b7e6?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c65cfd3b7e6</guid>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 22:37:13 GMT</pubDate>
            <atom:updated>2024-01-03T01:06:25.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdTN7AprzuJYfP4f5O7Osw.jpeg" /></figure><p>Cuando hablamos de paginación, ¿cuál es el primer enfoque que te viene a la mente? En mi caso, inmediatamente pienso en ‘LIMIT’ y ‘OFFSET’, así que los utilizo. ¿Es bueno, verdad? Bueno, en mi caso, me di cuenta de que era ineficiente para paginaciones grandes.</p><p>Profundicemos un poco más en esto.</p><h3>1. Configuración</h3><p>He creado una demostración sencilla con una tabla de ‘usuarios’ poblada con 10 millones de filas.</p><pre>-- Create the user table<br>CREATE TABLE users (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(100),<br>    gender VARCHAR(10)<br>);<br><br>-- Generate and insert 10 million rows using generate_series<br>INSERT INTO users (name, gender)<br>SELECT<br>    &#39;User &#39; || gs.num AS name,<br>    CASE WHEN gs.num % 2 = 0 THEN &#39;Male&#39; ELSE &#39;Female&#39; END AS gender<br>FROM generate_series(1, 10000000) AS gs(num);</pre><h3>2. SQL LIMIT y OFFSET</h3><p>LIMIT y OFFSET te permiten recuperar un subconjunto de filas de la consulta.</p><p>Escribamos la consulta SQL para la paginación.</p><pre>SELECT * FROM users ORDER BY id LIMIT 500 OFFSET 1000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*r5Qy8JMeBjdD8khEb2xKNg.png" /></figure><p>Para mí, esto parece magia. ¿Cómo sabe Postgres saltar esos registros? Bueno, en realidad no sabe cómo saltar esos registros.</p><p>Analicemos la consulta SQL con el comando ‘EXPLAIN ANALYZE’.</p><pre>EXPLAIN ANALYZE SELECT * FROM users ORDER BY id LIMIT 500 OFFSET 1000;</pre><p>Después de ejecutar la consulta SQL, obtuvimos el plan de la consulta y las estadísticas de ejecución.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*f6a4FwDGUR1veyBsU4lRLQ.png" /></figure><p>Adentrémonos en detalle en el plan de la consulta.</p><p>El plan de la consulta consta de dos partes:</p><p>En primer lugar, observamos que Postgres elige un Index Scan en la primary key ya que estamos ordenando los resultados según el ‘id’ utilizando la cláusula ORDER BY. En segundo lugar, Postgres limita los resultados para devolver las filas requeridas.</p><p>Si examinamos el tiempo real y las filas recuperadas por Postgres, vemos que en realidad son 1500 en lugar de 500.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*6DAe_gpQcM05XKoulhXP2A.png" /></figure><p>Esto significa que al utilizar LIMIT y OFFSET no se omiten los registros, se recuperan todos los registros en memoria y recae en que Postgres los filtre.</p><p>Si nos referimos a la documentación de PostgreSQL, encontramos que esto es realmente así. ‘Las filas omitidas por una cláusula OFFSET aún deben calcularse dentro del servidor; por lo tanto, un OFFSET grande podría ser ineficiente’.</p><p>Podemos decir que LIMIT y OFFSET funcionan bien con offsets pequeños, pero ¿existe un enfoque mejor para offsets más grandes?</p><h3>3. ¿Existe un enfoque mejor para un OFFSET grande?</h3><p>Podemos aprovechar el ID secuencial para obtener el mismo resultado con mayor eficiencia.</p><pre>SELECT * FROM users WHERE id between 1001 and 1500;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*XyH11i7yytoRe_6D8MLptw.png" /></figure><p>Analicemos la consulta.</p><pre>EXPLAIN ANALYZE SELECT * FROM users WHERE id between 1001 and 1500;</pre><p>Después de ejecutar la consulta, podemos ver que recupera solo las 500 filas requeridas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*sJ4MB7S2TyBqDWioM7IxsQ.png" /></figure><h3>4. Conclusión</h3><p>Podemos concluir que aunque el uso de LIMIT y OFFSET para la paginación puede funcionar bien para offsets pequeños, para offsets más grandes, podría ser ineficiente ya que debe cargar todo en memoria y filtrar las filas. Hay otras formas de lograr el mismo resultado. Aprovechar columnas ordenadas e índices podría ser un enfoque mejor para desplazamientos más grandes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c65cfd3b7e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cómo migré una base de datos transaccional de PostgreSQL de 3TB.]]></title>
            <link>https://geronimovelasco.medium.com/c%C3%B3mo-migr%C3%A9-una-base-de-datos-transaccional-de-postgresql-de-3tb-ff8245657647?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8245657647</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[challenges-and-growth]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 21:31:04 GMT</pubDate>
            <atom:updated>2025-01-19T19:49:09.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cómo migré una base de datos transaccional PostgreSQL de 3TB.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Zwqx1muVWiT2kDJbM8twQ.png" /><figcaption>Cómo migré una base de datos transaccional de PostgreSQL de 3TB.</figcaption></figure><blockquote>Utilicé ChatGPT para ayudarme a escribir este artículo porque quería que la lectura del artículo fuera realmente agradable. Soy bastante torpe para escribir artículos bien estructurados. La primera vez que intenté escribir el artículo fue como una montaña rusa hablando de todo y nada al mismo tiempo, ¡jaja!</blockquote><p>En el acelerado mundo de las startups, no es raro que equipos pequeños de desarrolladores se encarguen de un proyecto completo. Experimenté esto de primera mano como desarrollador full stack en una consultora de transporte, donde me convertí en el único responsable de un proyecto crítico. Con mis compañeros de equipo habiendo pasado a otras empresas, la responsabilidad de enfrentar los desafíos del proyecto recayó completamente en mis hombros.</p><p>Nuestro proyecto se enfocaba en gestionar transacciones dentro de sistemas de transporte, procesar datos entrantes para crear informes e información esencial. Al lidiar con un flujo constante de nuevas transacciones, quedó claro que necesitábamos una solución de base de datos confiable y eficiente.</p><p>En medio del ajetreo diario de administrar el sistema, recibimos una solicitud de cliente que cambiaría el juego: migrar nuestra colosal base de datos transaccional PostgreSQL de 3TB de AWS a Azure DevOps. El motivo detrás de este movimiento era cristalino: consolidar todo nuestro sistema dentro del ecosistema de Azure, optimizando operaciones y liberando el potencial de crecimiento.</p><p>Sin embargo, el reloj estaba en marcha; nos enfrentábamos a un desafiante reto. El cliente estableció un plazo ajustado, otorgándonos apenas 3 semanas para llevar a cabo toda la migración. La urgencia de la tarea agregó una capa adicional de presión, ya que sabíamos que el éxito del proyecto dependía de una planificación meticulosa, una ejecución impecable y un toque de innovación.</p><p>En este artículo, compartiré mis valiosas experiencias e ideas obtenidas durante el proceso de migración. Aunque no soy un experto en PostgreSQL, mi trayecto como un desarrollador solitario navegando esta tarea compleja estuvo lleno de desafíos, descubrimientos significativos y el desarrollo de mejores prácticas que creo serán de gran valor para otros que enfrenten situaciones similares. Migrar una base de datos de este tamaño requirió una planificación cuidadosa, toma de decisiones estratégicas y una comprensión profunda de las complejidades involucradas.</p><h3>Fasé de preparación</h3><p>La fase de preparación resultó ser una de las etapas más complicadas de la migración. La historia del proyecto, con intentos fallidos previos de migrar la base de datos utilizando pg_dump cuando tenía un tamaño de 2TB, me dejó incierto sobre cómo proceder. Aunque tenía un conocimiento general del tamaño de la base de datos y había desarrollado funciones y consultas complejas para ella, la magnitud de más de 200 tablas hizo que la tarea fuera mucho más compleja de lo que imaginé inicialmente.</p><p>Para abordar este desafío, el primer paso fue crear un mapeo completo de toda la base de datos. Documenté meticulosamente las columnas críticas, índices, relaciones, restricciones, disparadores y las tablas afectadas por ellos, así como las secuencias esenciales. Este mapeo nos proporcionó una imagen clara de lo que tenía por delante, lo que me permitió analizar y prepararme para la migración de la mejor manera posible.</p><p>Además, me gustaría agregar que este proceso me llevó casi una semana completarlo. Durante este tiempo, una preocupación crucial que pesaba sobre nosotros era el flujo continuo de nuevas transacciones, lo que causaba que la base de datos principal creciera constantemente. Los métodos tradicionales de copia de seguridad y restauración podrían llevar a una desincronización de datos, y detener la producción durante la migración no era una opción debido a la naturaleza crítica de nuestros servicios.</p><p>Al no estar familiarizado con las copias de seguridad incrementales y enfrentar limitaciones de tiempo, discutí la situación con el líder técnico y juntos ideamos un enfoque alternativo. El plan consistía en redirigir las nuevas transacciones entrantes a otra base de datos mientras yo me centraba en migrar la base de datos existente de 3TB. Este enfoque significaba que teníamos que manejar la migración no solo de la base de datos de 3TB, sino también de la nueva que estaba gestionando las transacciones entrantes.</p><p>A pesar de su complejidad, este enfoque alternativo prometía ahorrar tiempo y esfuerzo al migrar la base de datos más pequeña por separado. A pesar de los desafíos, logramos completar la migración con éxito, asegurando una interrupción mínima en las operaciones en curso. La experiencia me enseñó valiosas lecciones sobre cómo manejar proyectos de migración de bases de datos a gran escala de manera eficiente y responsable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*IE1oC9dfJUYjMsB6.png" /><figcaption>Database preparation strategy</figcaption></figure><h3>Elegir el enfoque de migración adecuado</h3><p>Después de analizar la base de datos, me encontré considerando diferentes enfoques de migración. La primera opción fue utilizar pg_dump/pg_restore, a pesar de nuestros intentos fallidos anteriores con este método. Otro enfoque consistía en utilizar Pentaho, una herramienta de integración de datos conocida por su versatilidad en el manejo de conjuntos de datos grandes. Por último, mi líder técnico sugirió un método de paginación manual utilizando el comando “offset limit”, lo cual llamó mi atención durante una demostración.</p><p>Permíteme explicarte estos tres enfoques de migración y sus respectivos resultados, así como los desafíos que enfrentamos en el camino. A pesar del atractivo inicial de cada método, finalmente nos decidimos por un enfoque que resultó ser el más adecuado para nuestra situación única.</p><h4>Pentaho</h4><p>El historial del proyecto con intentos fallidos utilizando pg_dump/pg_restore hizo que el enfoque de Pentaho fuera la primera opción a probar. Para determinar si Pentaho era un candidato adecuado para la migración, realicé una demostración simple, tratando de migrar la información de una tabla masiva con aproximadamente 700 millones de registros y alrededor de 40 columnas.</p><p>Después de configurar el entorno durante el día, dejé la migración en ejecución durante toda la noche para evaluar su rendimiento hasta el día siguiente.</p><p>A la mañana siguiente, al verificar el progreso de la migración, me desilusioné al descubrir la aparición del evento de espera “IODataFileRead”. Esto fue preocupante porque indicaba que la migración tenía dificultades para obtener los datos necesarios del disco. Incluso después de más de 12 horas, solo se habían migrado alrededor de 250,000 registros, dejándome sorprendido por los resultados poco impresionantes. Comencé a analizar las razones detrás de este problema.</p><p>En ese momento, mis pensamientos se centraron en el tamaño de la tabla y el alto número de columnas. Parecía que el tamaño de página predeterminado de 8 KB en la base de datos era insuficiente para manejar una tabla tan grande, lo que hacía que la base de datos obtuviera numerosas páginas, potencialmente en orden aleatorio, lo que provocaba que la obtención de datos se atascara. Como resultado, la base de datos tenía que recuperar miles de páginas de esta manera y almacenarlas en la memoria RAM antes de devolverlas, lo que ralentizaba significativamente el proceso de migración.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*IoLEkWCGfvb4tqso.png" /></figure><p>Después de realizar múltiples demostraciones con tablas similares, con la esperanza de encontrar una forma de hacer que el enfoque de Pentaho funcionara, lamentablemente no obtuve los resultados deseados. A medida que el reloj seguía avanzando, el tiempo se volvía un bien preciado.</p><p>Dedicé cuatro días a trabajar en este enfoque, pero a pesar de mis esfuerzos, quedó claro que no era la opción adecuada para nuestros requisitos de migración. Con el plazo acercándose y la necesidad de explorar otras opciones, tomé la difícil decisión de pasar al siguiente enfoque. Adaptarme rápidamente y tomar decisiones informadas se volvió crucial como desarrollador solitario encargado de este proyecto crítico.</p><p>La migración de una base de datos de tal envergadura requería una estrategia efectiva y un enfoque sólido. Aunque el enfoque de Pentaho no funcionó como se esperaba, este proceso de prueba y error fue valioso, ya que me permitió descartar una opción que no se ajustaba a nuestras necesidades. Siempre es importante aprender de las dificultades y ajustar el enfoque para encontrar la mejor solución.</p><p>En el siguiente paso, me embarqué en explorar el método de paginación manual utilizando “offset limit”, que fue sugerido por mi líder técnico. Este enfoque presentó ciertas ventajas, como una mayor flexibilidad y control sobre el proceso de migración. A través de esta experiencia, seguí aprendiendo y creciendo como profesional, enfrentando los desafíos con determinación y perseverancia.</p><h4><strong>El método de paginación manual utilizando “offset limit”</strong></h4><p>Mientras se ejecutaba la demostración de la migración con Pentaho, aproveché parte del tiempo libre para explorar otras posibilidades. Mi líder técnico sugirió probarlo, aunque yo estaba escéptico sobre su éxito. Sorprendentemente, durante este tiempo, me topé con algo intrigante.</p><p>Decidí crear un proyecto simple en NodeJS para obtener información de la tabla con 700 millones de registros utilizando la paginación con un offset de 100,000 registros y un valor límite de 100,000. Para mi sorpresa, cuando la consulta alcanzó aproximadamente 220 millones de registros, de repente tuvo dificultades y quedó atascada, activando el temido evento de espera “IODataFileRead”. Me quedé perplejo por esta desaceleración repentina y decidí realizar un análisis exhaustivo para entender la causa raíz.</p><p>Durante mi investigación, descubrí algo interesante sobre el offset. Ejecuté el comando “EXPLAIN ANALYZE” en la consulta para obtener una comprensión más profunda del proceso de ejecución real de PostgreSQL. Esta exploración me permitió obtener una comprensión más profunda del comportamiento de la base de datos y los desafíos que enfrentaba al manejar conjuntos de datos tan grandes.</p><p><strong>Query example</strong></p><pre>EXPLAIN ANALYZE SELECT * FROM table_name offset 200000 limit 100000;</pre><p>Usar OFFSET en realidad no salta registros; más bien, recupera todos los registros y confía en PostgreSQL para filtrarlos. Esto explica por qué la consulta se estaba ralentizando, ya que no estaba recuperando solo los 100,000 registros esperados, sino todos los 220 millones de registros, solo para filtrarlos después. Fue una observación intrigante y confirmó aún más mis sospechas iniciales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*a6t_DNE2K-9bGvNJ.png" /></figure><p>Mientras explorábamos opciones alternativas, consideramos usar el comando COPY para realizar copias de seguridad de manera paginada. Sin embargo, surgió un obstáculo desafortunado. Las tablas de la base de datos tenían índices primarios que contenían valores UUID, lo que hacía que este enfoque fuera inviable. La presencia de UUIDs perturbaba el orden de las tablas, lo que hacía impráctico utilizar eficientemente el comando COPY para la migración.</p><p><strong>Query example</strong></p><pre>COPY (SELECT * FROM your_table WHERE id BETWEEN 1 AND 100) TO &#39;/table-backup.csv&#39; CSV HEADER;</pre><p>Este descubrimiento nos llevó a un punto de decisión crítico, que nos obligó a reevaluar nuestro enfoque y buscar un método que pudiera funcionar eficazmente a pesar de las limitaciones impuestas por los índices principales de UUID. Como desarrollador solitario, encontrar una solución adecuada en medio de estos desafíos requirió una combinación de creatividad y experiencia técnica.</p><h4>pg_dump y pg_restore</h4><p>Después de una semana entera de trabajar en dos enfoques diferentes, el último enfoque que probé fue utilizando pg_dump y pg_restore. Durante este tiempo, tomé la iniciativa de investigar estos comandos para comprender mejor cómo utilizarlos de manera efectiva para un rendimiento óptimo.</p><p>Sin embargo, hubo un desafío significativo al tratar con Azure For PostgreSQL: Flexible server; no teníamos acceso como superusuario. Esta limitación planteó un problema, ya que la estrategia ideal habría sido deshabilitar los disparadores durante el proceso de migración para acelerar la restauración. Desafortunadamente, esto no fue posible debido a la falta de acceso como superusuario. Este contratiempo me obligó a buscar formas alternativas de lograr una migración eficiente.</p><p>A lo largo del proceso, mantuve al cliente informado sobre los desarrollos en curso, ya que ya habíamos superado la fecha límite inicial, haciéndoles conscientes de que la tarea era compleja. En un esfuerzo por abordar los desafíos, el cliente incluso contrató a un experto en PostgreSQL para ayudarnos, pero después de dos semanas adicionales de esfuerzos colaborativos, aún no logramos una migración exitosa. En consecuencia, el cliente extendió la fecha límite para acomodar las complejidades que encontramos.</p><p>Después de casi dos semanas de investigación intensiva y extensos experimentos con múltiples estrategias utilizando pg_dump y pg_restore, he creado con éxito un plan integral para acelerar el proceso de migración tanto para la base de datos de 3TB como para la base de datos más pequeña.</p><ol><li><strong>Utilizando 0 compresión para pg_dump (-Z 0):</strong> Al especificar el parámetro -Z 0 durante la fase de respaldo, opté por 0 compresión, priorizando la velocidad sobre la utilización del espacio en disco. Esta decisión aceleró el proceso de respaldo, aunque requirió espacio adicional en el disco para almacenar la copia de seguridad.</li><li><strong>Empleando trabajos para respaldos y restauraciones concurrentes (-j &lt;num&gt;):</strong> Para mejorar aún más el rendimiento general y reducir el tiempo de migración, utilicé el procesamiento en paralelo mediante el parámetro -j &lt;num&gt; para manejar respaldos y restauraciones de manera concurrente para diversas tablas. Al establecer &lt;num&gt; como el número deseado de trabajos en paralelo, ejecuté múltiples tareas simultáneamente, lo que aumentó significativamente la eficiencia del proceso de migración.</li><li><strong>Deshabilitando disparadores durante la restauración ( — disable-triggers): </strong>Para mantener la consistencia de los datos y evitar conflictos derivados de la ejecución de disparadores, deshabilité los disparadores durante la fase de restauración utilizando el parámetro — disable-triggers. Esta precaución aseguró evitar problemas de integridad durante la restauración de datos.</li></ol><p>Mi plan paso a paso fue el siguiente:</p><ol><li>Respaldar el esquema de la base de datos y migrar secuencias mientras se crean los roles de base de datos necesarios en el nuevo servidor.</li><li>Eliminar restricciones clave para reducir operaciones de E/S innecesarias y mejorar la velocidad de migración.</li><li>Quitar índices grandes para optimizar aún más las operaciones de E/S durante la migración.</li><li>Migrar la información tabla por tabla o en grupos de tablas relacionadas. Debido a la falta de permisos de superusuario, tuve que seleccionar cuidadosamente las relaciones clave a eliminar para lograr un proceso de migración más fluido.</li><li>Después de migrar la información, restaurar las restricciones, teniendo en cuenta las relaciones entre las tablas.</li><li>Finalmente, restaurar los índices grandes de manera concurrente después de migrar con éxito los datos.</li></ol><p>Una vez que finalicé el plan de migración, lo revisé con mi líder técnico y comencé a configurar el entorno para iniciar el proceso real de migración de la base de datos, lo que me permitió superar las limitaciones impuestas por la falta de permisos de superusuario.</p><h3>Configuración del entorno de migración</h3><p>Para configurar el entorno de migración, hemos decidido utilizar una Máquina Virtual (VM) para realizar copias de seguridad y llevar a cabo la restauración en la base de datos final. La VM se creará en la misma región que la base de datos de destino. Para garantizar una comunicación segura y eficiente entre los recursos de Azure, configuraremos los permisos necesarios para permitir que la VM se conecte a la base de datos mediante Azure VNET (Red Virtual).</p><p>El uso de Azure VNET para la comunicación entre los recursos tiene ventajas, ya que ofrece un mejor rendimiento y seguridad en comparación con la comunicación a través de Internet público.</p><p>Estos son los pasos que se han seguido para preparar la VM para la migración:</p><ol><li><strong>Crear la VM:</strong> Se ha creado una Máquina Virtual en la misma región de Azure que la base de datos final. Esto garantiza proximidad, lo que puede mejorar la velocidad de transferencia de datos.</li><li><strong>Instalar PostgreSQL:</strong> Una vez configurada la VM, se instaló PostgreSQL en ella. Esto servirá como nuestro servidor de migración, donde almacenaremos los archivos de copia de seguridad de la base de datos y realizaremos la restauración.</li><li><strong>Configurar Permisos y Redes:</strong> Para establecer una conexión segura y eficiente entre la VM y la base de datos de destino, se configuraron los permisos y ajustes de red necesarios. Utilizando Azure VNET, podemos garantizar que la comunicación esté restringida a la red virtual, reduciendo la exposición a Internet público y mejorando la seguridad en general.</li><li>Probar Conexiones: Con PostgreSQL instalado y la configuración de red establecida, se llevaron a cabo pruebas de conexión para verificar que la VM pueda comunicarse con las bases de datos de origen y destino de manera exitosa. Este paso es crucial para asegurar que el proceso de migración pueda continuar sin problemas de conectividad.</li></ol><p>En este punto, la VM está lista para funcionar como el servidor de migración, y estamos preparados para proceder con la migración de la base de datos. Los próximos pasos implicarán tomar copias de seguridad de la base de datos de origen, transferirlas de manera segura a la VM y luego restaurar los datos en la base de datos final.</p><h3>Ejecución de la migración</h3><p>El día de la migración de la base de datos de 3TB, me preparé meticulosamente siguiendo el plan establecido. Antes de ejecutar cualquier operación de respaldo o restauración, me aseguré de ajustar finamente los parámetros en el postgresql.conf para optimizar el rendimiento y evitar posibles problemas, como vacíos automáticos. Consulté los parámetros recomendados de recursos de Azure, asegurándome de seguir las mejores prácticas al utilizar pg_dump y pg_restore.</p><p>Una vez que la configuración estuvo optimizada, procedí a crear scripts de respaldo y restauración, simplificando el proceso y eliminando la necesidad de entrada manual. Verifiqué dos veces los scripts para asegurarme de su precisión antes de iniciar cualquier comando.</p><p>Con todo listo, informé al equipo y al cliente sobre el inicio del proceso de migración y comencé a ejecutar cada paso descrito en el plan. Durante la migración, monitoreé de cerca el progreso, asegurándome de que cada fase se ejecutara según lo previsto. Comunicando regularmente el estado y las actualizaciones al equipo, mantuve a todos informados sobre el progreso de la migración.</p><p>Gracias a la meticulosa preparación y el seguimiento del plan, logré gestionar con éxito el proceso de migración, garantizando una transición fluida y eficiente para la base de datos de 3TB. La combinación de configuración optimizada, scripts automatizados y comunicación constante contribuyó a la finalización exitosa de la migración.</p><p>Informamos al cliente que las transacciones entrantes se encolarían durante el proceso de migración de la base de datos más grande de 3TB. Mientras se llevaba a cabo la migración de la base de datos más pequeña, enfocamos nuestros esfuerzos en asegurar una migración fluida y eficiente para la más pequeña, que tomó menos tiempo en completarse.</p><p>Durante la migración de la base de datos más pequeña, continuamos gestionando las transacciones entrantes de manera efectiva y aseguramos que no se perdiera ni comprometiera ningún dato. Una vez que la migración de la base de datos más pequeña se completó con éxito, reanudamos la recepción de transacciones para ambas bases de datos.</p><p>Le comunicamos al cliente que las transacciones entrantes se pondrían en cola durante el proceso de migración de la base de datos más pequeña. Durante la migración de la base de datos más pequeña, continuamos administrando las transacciones entrantes de manera efectiva y nos aseguramos de que no se perdiera ni se comprometiera ningún dato. Una vez que se completó con éxito la migración de la base de datos más pequeña, completamos la migración, unificamos la información y reanudamos la recepción de transacciones en el nuevo entorno.</p><h3>Monitoreo e Integridad de Datos</h3><p>Durante el proceso de migración, garantizar la integridad de los datos y monitorear el progreso son aspectos críticos. Para lograr esto, empleé tres métodos de monitoreo:</p><ol><li><strong>Monitoreo de Red: </strong>Supervisé la Máquina Virtual (VM) y el Servidor de la Base de Datos utilizando herramientas de monitoreo de red para observar el flujo de datos entre ellos. Al mantener un estrecho seguimiento de la actividad de la red, pude asegurarme de que la información se estuviera migrando según lo esperado e identificar cualquier problema relacionado con la red que pudiera afectar la migración.</li><li><strong>PgAdmin Dashboard:</strong> El Panel de Control de PgAdmin proporcionaba información en tiempo real sobre el progreso del proceso de pg_restore. Al monitorear el panel, pude rastrear la ejecución de las tareas de restauración, identificar cualquier evento de espera y observar la salud general de la base de datos durante la migración.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9_EhkZMPhpLx8tyV.png" /></figure><p><strong>3. Consultas de Metadatos de la Base de Datos:</strong> Con frecuencia utilicé diversas consultas para verificar los metadatos de la base de datos, lo que me permitió asegurarme de que la información se migrara correctamente y verificar la integridad de los datos. Algunas de las consultas más importantes que utilicé incluyeron:</p><ul><li><strong>Tuplas Vivas y Muertas:</strong> Supervisé la cantidad de tuplas vivas y muertas en las tablas para evaluar cuánto espacio se estaba utilizando y cómo se distribuían los datos. Esto ayudó a identificar posibles problemas con la distribución de datos y la utilización del espacio durante la migración.</li></ul><pre>SELECT relname, n_live_tup, n_dead_tup <br>FROM pg_stat_all_tables <br>WHERE n_live_tup &gt; 0 OR n_dead_tup &gt; 0;<br><br>-- TO SEARCH FOR A SPECIFIC TABLE<br>SELECT relname, n_live_tup, n_dead_tup <br>FROM pg_stat_all_tables <br>WHERE relname = &#39;table_name&#39;;</pre><ul><li><strong>Tamaño de la Tabla</strong>: Verifiqué regularmente el tamaño de las tablas para hacer un seguimiento del progreso de la migración de datos. Esto me permitió asegurarme de que las tablas se estuvieran llenando con datos según lo esperado y ayudó a identificar cualquier discrepancia que pudiera indicar problemas de migración.</li></ul><pre>SELECT<br>    relname AS &quot;relation&quot;,<br>    pg_size_pretty (<br>        pg_total_relation_size (C .oid)<br>    ) AS &quot;total_size&quot;<br>FROM<br>    pg_class C<br>LEFT JOIN pg_namespace N ON (N.oid = C .relnamespace)<br>WHERE<br>    nspname NOT IN (<br>        &#39;pg_catalog&#39;,<br>        &#39;information_schema&#39;<br>    )<br>AND C .relkind &lt;&gt; &#39;i&#39;<br>AND nspname !~ &#39;^pg_toast&#39;<br>and relname = &#39;table_name&#39;<br>ORDER BY<br>    pg_total_relation_size (C .oid) DESC</pre><ul><li><strong>Tamaño de la Base de Datos: </strong>Monitorear el tamaño general de la base de datos.</li></ul><pre>SELECT pg_size_pretty(<br>        pg_database_size( current_database() )<br> ) AS database_size;</pre><p>Utilizando estos métodos de monitoreo y ejecutando consultas esenciales, pude asegurar con confianza el éxito del proceso de migración, mantener la integridad de los datos y abordar cualquier problema de manera oportuna durante la migración.</p><h4>Optimizaciones posteriores a la migración</h4><p>Ajusté los valores de la configuración de PostgreSQL, ajustando finamente los parámetros del servidor postgresql.conf para lograr un mejor rendimiento. Por defecto, Azure For PostgreSQL ajusta automáticamente estos parámetros según los recursos del servidor. Sin embargo, los ajusté para optimizar aún más la configuración de la base de datos.</p><h4>Pensamientos y sentimientos personales</h4><p>Al principio, debo admitir que veía la migración como una tarea imposible. Incluso con la ayuda del desarrollador senior y el arquitecto de software del equipo, luchamos solo para hacer copias de seguridad de la base de datos en el pasado. Cuando el cliente hizo la solicitud, sabía que recaería sobre mis hombros manejarla, y no tenía a nadie más a quien recurrir para obtener ayuda, ya que era el único que quedaba del equipo original.</p><p>Para ser honesto, incluso los otros equipos y mis líderes técnicos tenían miedo de la solicitud. Y yo también me sentía de la misma manera. Pero luego recordé un consejo de un creador de contenido realmente bueno llamado midudev. Él dijo que si nadie más quiere tocar un proyecto, ni siquiera con un palo, podría ser una oportunidad para desafiarse a sí mismo, aprender mucho y convertirse en un mejor ingeniero de software.</p><p>Así que, con esa mentalidad, decidí abrazar el desafío de manera positiva. Sabía que no era un experto en PostgreSQL en absoluto, pero tenía algo de experiencia migrando bases de datos más pequeñas de 5GB o 20GB. Sin embargo, manejar una masiva base de datos transaccional de 3TB era una historia completamente diferente.</p><p>A pesar de mi miedo inicial, di el salto y lideré la migración. Debo decir que este desafío sacó lo mejor de mí. Me complace decir que completé con éxito la migración e incluso encontré formas de optimizar ciertos aspectos de la base de datos.</p><p>A lo largo del proceso, aprendí muchísimo. La migración realmente me ayudó a comprender los fundamentos de las bases de datos y cómo funcionan detrás de escena. Fue una experiencia increíblemente enriquecedora para mí como profesional.</p><p>Mirando hacia atrás, si me enfrentara a la misma situación nuevamente, me acercaría de la misma manera que lo hice antes. El sentido de logro y el conocimiento adquirido realmente lo valieron.</p><p>Ahora que sé un poco más sobre PostgreSQL, definitivamente consideraría usar otras herramientas de migración como Barman o pgcopydb para copias de seguridad incrementales y tareas de migración más avanzadas. La migración manual puede ser propensa a errores, y estas herramientas pueden proporcionar más automatización y confiabilidad.</p><p>He decidido escribir este artículo para compartir toda mi experiencia de migración. Creo que podría ser útil para alguien más que se encuentre en una situación similar. Compartir mi viaje y las lecciones que he aprendido podría ofrecer perspectivas valiosas y aliento a otros que enfrentan migraciones desafiantes.</p><h4>Conclusión</h4><p>En conclusión, migrar una base de datos masiva de 3TB fue una tarea desafiante y compleja. Requirió un conocimiento profundo de los fundamentos de las bases de datos e involucró un proceso de prueba y error. A pesar de las dificultades, aprendí lecciones valiosas y obtuve un conocimiento más profundo de PostgreSQL.</p><p>El monitoreo del progreso de la migración fue crucial para mantener la integridad de los datos y el rendimiento. La experiencia me impulsó a sobresalir y optimizar la base de datos con éxito.</p><p>Mirando hacia el futuro, estoy ansioso por explorar otras herramientas de migración para futuros proyectos. Escribir este artículo ha sido un viaje de reflexión y espero que pueda inspirar y ayudar a otros que enfrenten desafíos similares. En general, la experiencia de migración ha fortalecido mis habilidades como ingeniero de software y ha reafirmado mi dedicación para abrazar desafíos técnicos.</p><h4>Referencias</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8245657647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Migrated a 3 TB PostgreSQL Transactional Database]]></title>
            <link>https://medium.com/better-programming/how-i-migrated-a-3tb-postgresql-transactional-database-ee1cf85c37bf?source=rss-f26913ebede0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1cf85c37bf</guid>
            <category><![CDATA[challenges-and-growth]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Geronimo Velasco]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 19:04:36 GMT</pubDate>
            <atom:updated>2023-08-14T17:58:40.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Zwqx1muVWiT2kDJbM8twQ.png" /><figcaption>Images by author</figcaption></figure><blockquote>Disclaimer: I used ChatGPT’s assistance in composing this article because English is not my native language, and I wanted to make the reading really enjoyable. The first time I tried to write this article, it was like a roller coaster talking about everything and nothing at the same time. Ha, ha.</blockquote><p>In the fast-paced startup world, it’s not uncommon for small developer teams to handle an entire project. I experienced this firsthand as a full stack developer at a transport consultant, where I became the sole caretaker of a critical project. With my team members having moved on to other ventures, the responsibility to tackle the project’s challenges fell squarely on my shoulders.</p><p>Our project focused on managing transport system transactions and processing incoming data to create essential reports and information. Dealing with a constant influx of new transactions, it became evident that we needed a reliable and efficient database solution.</p><p>Amidst the daily hustle of managing the system, a game-changing client request landed on our desks: migrate our colossal 3 TB PostgreSQL Transactional Database from AWS to Azure DevOps. The motive behind this move was crystal clear — to consolidate our entire system within the Azure ecosystem, streamlining operations and unlocking the growth potential.</p><p>However, the clock was ticking; we faced a daunting challenge. The client set a tight deadline, granting us three weeks to execute the migration. The task&#39;s urgency added an extra layer of pressure, as we knew the success hinged on meticulous planning, flawless execution, and a touch of innovation.</p><p>In this article, I’ll share my valuable experiences and insights gained during migration. While I am not a PostgreSQL expert, my journey as a lone developer navigating this complex task was filled with challenges, significant discoveries, and the development of best practices that I believe will be of great value to others facing similar situations. Migrating such a sizable database demanded careful planning, strategic decision-making, and a deep understanding of the intricacies involved.</p><h3>Preparing for the Migration</h3><p>The preparation phase proved to be one of the most intricate stages of the migration. The project’s history of unsuccessful attempts to migrate the database using pg_dump, back when it was a 2 TB database had left me uncertain about how to proceed. Although I had a general understanding of the database’s size and had developed features and complex queries for it, the sheer magnitude of over 200 tables made the task far more complex than I initially imagined.</p><p>To tackle this challenge, the first step was to map the entire database comprehensively. I meticulously documented critical columns, indexes, relationships, constraints, triggers, tables affected by them, and the essential sequences. This mapping gave us a clear picture of what I was up against, enabling me to analyze and prepare for the migration in the best possible way.</p><p>Additionally, this process took me almost a week to complete. During this time, one crucial concern that loomed over us was the continuous influx of new transactions, causing the main database to grow incessantly.</p><p>Traditional backup and restore methods could lead to desynchronization of data, and halting production during migration was not an option due to the critical nature of our services.</p><p>Being unfamiliar with incremental backups and facing time constraints, I discussed the situation with the technical leader, and together, we devised an alternative approach. The plan involved redirecting the new incoming transactions to another database while I focused on migrating the existing 3 TB database. This approach meant we had to handle the migration of the 3TB database and the new one handling incoming transactions.</p><p>Though complex, this alternative approach promised to save time and effort in migrating the smaller database separately. Despite the challenges, we completed the migration successfully, ensuring minimal disruption to the ongoing operations. The experience taught me valuable lessons in handling large-scale database migration projects efficiently and responsibly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*xY2PD6XsDD_9rSE7T2XPhg.png" /><figcaption>Database preparation strategy</figcaption></figure><h3>Choosing the Right Migration Approach</h3><p>After analyzing the database, I found myself considering different migration approaches. The first option was using pg_dump/pg_restore, despite our unsuccessful attempts with this method. Another approach involved Pentaho, a data integration tool known for its versatility in handling large datasets. Lastly, a manual pagination method using an offset limit was suggested by my technical leader, which caught my attention during a demo.</p><p>Let me walk you through these three migration approaches, their respective outcomes, and the challenges we encountered. Despite the initial appeal of each method, we eventually settled on one approach that proved to be the most suitable for our unique situation.</p><h4>Pentaho</h4><p>The project’s history of unsuccessful attempts with pg_dump/pg_restore made the Pentaho approach the first option to try. To determine if Pentaho was a suitable candidate for the migration, I conducted a simple demo, attempting to migrate the information from a massive table with approximately 700 million records and around 40 columns.</p><p>After setting up the environment during the day, I left the migration running all night to assess its performance until the next day.</p><p>The following morning, upon checking the migration’s progress, I was disheartened to discover the occurrence of the IODataFileRead wait event. This was concerning because it indicated that the migration was struggling to fetch necessary data from the disk. Even after over 12 hours, only around 250 million records had been migrated, leaving me shocked by the lackluster results. I began to analyze the reasons behind this issue.</p><p>At that moment, my thoughts centered on the table’s size and the high number of columns. It appeared the database&#39;s default 8 kb page size was insufficient for handling such a large table, causing the database to fetch numerous pages, potentially in random order, leading to data fetching getting stuck. As a result, the database had to retrieve thousands of pages in this manner and store them in RAM before returning them, significantly slowing down the migration process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*b6ZO29gKPSjnrws0CZuO_g.png" /></figure><p>I attempted multiple demos with similar tables, hoping to find a way to make the Pentaho approach work, but unfortunately, it did not yield the desired results. As the clock continued ticking, time was becoming a precious commodity.</p><p>I dedicated four days to working on this approach, but despite my efforts, it became evident that there were better fits for our migration requirements. With the deadline looming and the need to explore other options, I decided to move on to the next approach. Adapting quickly and making informed decisions became paramount as a solo developer handling this critical project.</p><h4>Manual pagination method using offset limit</h4><p>While the demo of the Pentaho migration ran, I used some of the downtime to explore other possibilities. My technical leader suggested trying it out, although I was skeptical about its success. Surprisingly, during this time, I stumbled upon something intriguing.</p><p>I created a simple NodeJS project to fetch information from the table with 700 million records using pagination with an offset of 100,000 records and a limit value of 100,000. Surprisingly, when the query reached around 220 million records, it suddenly struggled and stuck, triggering the dreaded IODataFileRead wait event. I was perplexed by this sudden slowdown and decided to conduct a thorough analysis to understand the root cause.</p><p>During my investigation, I learned something interesting about the offset. I executed the EXPLAIN ANALYZE command on the query to gain deeper insights into PostgreSQL’s execution process. This exploration allowed me to better understand the database’s behavior and the challenges it faced while handling such large datasets.</p><p><strong>Query example</strong></p><pre>EXPLAIN ANALYZE SELECT * FROM table_name offset 200000 limit 100000;</pre><p>Using OFFSET doesn’t skip records; instead, it fetches all the records and relies on PostgreSQL to filter them. This explains why the query was slowing down, as it wasn’t fetching just the expected 100,000 records but rather all 220 million records, only to be filtered afterward. It was an intriguing observation, and it further confirmed my initial suspicions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j02F193VMYujjmdQEXQmIg.png" /></figure><p>As we explored alternative options, we considered using the COPY command for backup in a paginated manner. However, an unfortunate obstacle presented itself. The database’s tables had primary indexes containing UUID values, rendering this approach unfeasible. The presence of UUIDs disrupted the table order, making it impractical to utilize the COPY command for the migration efficiently.</p><p><strong>Query example</strong></p><pre>COPY (SELECT * FROM your_table WHERE id BETWEEN 1 AND 100) TO &#39;/table-backup.csv&#39; CSV HEADER;</pre><p>This discovery led us to a critical decision point, requiring us to reevaluate our approach and search for a method that could work effectively despite the constraints imposed by the UUID primary indexes. As a solo developer, finding a suitable solution amidst these challenges demanded a blend of creativity and technical expertise.</p><h4>pg_dump/pg_restore</h4><p>After an entire week of working on two different approaches, the last approach I tried was using pg_dump and pg_restore. During this time, I took the initiative to research these commands to better understand how to use them effectively for optimal performance.</p><p>However, a significant challenge was dealing with Azure For PostgreSQL: flexible server. We didn’t have access as superusers. This limitation posed an issue since the ideal strategy would have been to disable triggers during the migration process to speed up the restore. Unfortunately, it wasn’t possible due to the lack of superuser access. This setback forced me to look for alternative ways to achieve the migration efficiently.</p><p>Throughout the process, I kept the client updated about the ongoing developments as we had already surpassed the initial deadline, making them aware that the task was complex. To address the challenges, the client even hired a PostgreSQL expert to assist us, but after an additional two weeks of collaborative efforts, we still hadn’t achieved a successful migration. Consequently, the client extended the deadline to accommodate the complexities we encountered.</p><p>After nearly two weeks of intensive research and extensive experimentation with multiple strategies using pg_dump and pg_restore, I have successfully crafted a comprehensive plan to expedite the migration process for the 3 TB and the smaller database.</p><ol><li>Utilizing 0 compression for pg_dump (-Z 0): By specifying the -Z 0 parameter during the backup phase, I opted for 0 compression, prioritizing speed over disk space utilization. This decision accelerated the backup process, even though it required additional disk space to store the backup.</li><li>Employing jobs for concurrent backups and restoration (-j &lt;num&gt;): To further improve overall performance and reduce migration time, I utilized parallel processing by using the -j &lt;num&gt; parameter to handle backups and restoration concurrently for various tables. By setting &lt;num&gt; to the desired number of parallel jobs, I executed multiple tasks simultaneously, significantly increasing the efficiency of the migration process.</li><li>Disabling triggers during restoration (--disable-triggers): To maintain data consistency and prevent conflicts arising from trigger executions, I disabled triggers during the restoration phase using the --disable-triggers parameter. This precaution ensured the avoidance of integrity issues during data restoration.</li></ol><p>My step-by-step plan was as follows:</p><ol><li>Backup the database schema and migrate sequences while creating the necessary database roles on the new server.</li><li>Delete key constraints to reduce unnecessary IO operations and improve migration speed.</li><li>Remove large indexes to optimize IO operations during migration further.</li><li>Migrate the information table by table or in groups of related tables. Due to the lack of superuser permissions, I had to carefully select the key relationships to delete for a smoother migration process.</li><li>After migrating the information, restore the constraints, keeping the relationships between tables in mind.</li><li>Finally, restore the huge indexes concurrently after successfully migrating the data.</li></ol><p>Once I had finalized the migration plan, I reviewed it with my technical leader. I began setting up the environment to initiate the actual database migration process, which allowed me to overcome the limitations posed by the lack of superuser permissions.</p><h3>Setting Up the Migration Environment</h3><p>To set up the migration environment, we have decided to use a Virtual Machine (VM) to take backups and perform the restoration in the final Database. The VM will be created in the same region as the destination database. To ensure secure and efficient communication between Azure resources, we will configure the necessary permissions to allow the VM to connect to the database using Azure VNET (Virtual Network).</p><p>Using Azure VNET for communication between resources is advantageous as it offers better performance and security than communication over the public internet.</p><p>Here are the steps taken to prepare the VM for the migration:</p><ol><li>Creating the VM: We created a Virtual Machine in the same Azure region as the final database. This ensures proximity, which can enhance data transfer speeds.</li><li>Installing PostgreSQL: Once the VM was set up, we installed PostgreSQL on it. This will serve as our migration server, where we’ll store the database backup files and perform the restoration.</li><li>Configuring Permissions and Networking: To establish a secure and efficient connection between the VM and the destination database, we configured the necessary permissions and networking settings. By utilizing Azure VNET, we can ensure that communication is restricted to the virtual network, reducing exposure to the public internet and improving overall security.</li><li>Testing Connections: With PostgreSQL installed and networking set up, we conducted connection tests to verify that the VM can successfully communicate with the source and destination databases. This step is crucial to ensure that the migration process can proceed smoothly without connectivity issues.</li></ol><p>At this point, the VM is ready to serve as the migration server, and we are prepared to proceed with the database migration. The next steps will involve taking backups from the source database, transferring them to the VM securely, and then restoring the data to the final database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYW-nr-r6svTrJQSReOVVw.png" /></figure><h3>Executing the Migration</h3><p>On the day of the 3 TB migration, I meticulously prepared by following the established plan. Before executing any backup or restore operations, I made sure to fine-tune the parameters in the postgresql.conf to optimize performance and avoid potential issues, such as auto vacuums. I referred to recommended parameters from Azure resources, ensuring adherence to best practices when using pg_dump and pg_restore.</p><p>Once the configuration was optimized, I created backup and restore scripts, streamlining the process and eliminating the need for manual input. I double-checked the scripts to ensure their accuracy before initiating any commands.</p><p>With everything in place, I informed the team and client about the migration process commencement and began executing each step outlined in the plan. Throughout the migration, I closely monitored the progress, ensuring each phase was executed as intended. Regularly communicating the status and updates to the team, I kept everyone informed about the migration’s progress.</p><p>By meticulously preparing and following the plan, I successfully managed the migration process, ensuring a smooth and efficient transition for the 3TB database. The combination of optimized configuration, automated scripts, and constant communication contributed to successfully completing the migration.</p><p>We communicated with the client that incoming transactions would be queued during the migration process of the smaller database. While migrating the smaller database, we managed the incoming transactions effectively and ensured that no data was lost or compromised. Once the migration of the smaller database was completed, we completed the migration, unified the information, and resumed the transaction reception in the new environment.</p><p>With all the information successfully migrated and transaction reception resumed, the system operated seamlessly in the new environment. We conducted thorough testing and validation to guarantee data integrity and consistent performance.</p><p>The client was pleased with the results, and the strategic handling of the migration process allowed us to minimize downtime and avoid any significant disruptions to their operations.</p><h3>Monitoring and Data Integrity</h3><p>During the migration process, ensuring data integrity and monitoring the progress are critical aspects. To achieve this, I employed three monitoring methods:</p><ol><li>Network Monitoring: I monitored the Virtual Machine (VM) and database server using network monitoring tools to observe the data flow between them. By closely monitoring the network activity, I could ensure that the information was being migrated as expected and identify any potential network-related issues that could impact the migration.</li><li>PgAdmin Dashboard: The PgAdmin Dashboard provided real-time insights into the progress of the pg_restore process. By monitoring the dashboard, I could track the execution of restoration tasks, identify any wait events, and observe the overall health of the database during the migration.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSWYernW9lQldiI2tZuqbw.png" /></figure><ol><li>Database Metadata Queries: I frequently used various queries to check the database metadata, which allowed me to ensure that the information was migrated successfully and verify data integrity. Some of the most important queries I used included:</li></ol><ul><li>Live and Dead Tuples: I monitored the number of live and dead tuples in the tables to gauge how much space was utilized and how well the data was distributed. This helped identify potential data distribution and space utilization issues during the migration.</li></ul><pre>SELECT relname, n_live_tup, n_dead_tup <br>FROM pg_stat_all_tables <br>WHERE n_live_tup &gt; 0 OR n_dead_tup &gt; 0;<br><br> -- TO SEARCH FOR A SPECIFIC TABLE<br><br>SELECT relname, n_live_tup, n_dead_tup <br>FROM pg_stat_all_tables <br>WHERE relname = &#39;table_name&#39;;</pre><ul><li>Table Size: I regularly checked the size of the tables to track the progress of data migration. This allowed me to ensure that the tables were being populated with data as expected and helped identify any discrepancies that could indicate migration issues.</li></ul><pre>SELECT<br>    relname AS &quot;relation&quot;,<br>    pg_size_pretty (<br>        pg_total_relation_size (C .oid)<br>    ) AS &quot;total_size&quot;<br>FROM<br>    pg_class C<br>LEFT JOIN pg_namespace N ON (N.oid = C .relnamespace)<br>WHERE<br>    nspname NOT IN (<br>        &#39;pg_catalog&#39;,<br>        &#39;information_schema&#39;<br>    )<br>AND C .relkind &lt;&gt; &#39;i&#39;<br>AND nspname !~ &#39;^pg_toast&#39;<br>and relname = &#39;table_name&#39;<br>ORDER BY<br>    pg_total_relation_size (C .oid) DESC</pre><ul><li>Database Size: Monitoring the overall size of the database.</li></ul><pre>SELECT pg_size_pretty(<br>        pg_database_size( current_database() )<br> ) AS database_size;</pre><p>By using these monitoring methods and running essential queries, I could confidently ensure the success of the migration process, maintain data integrity, and address any issues promptly during the migration.</p><h3>Post-Migration Optimizations</h3><p>I adjusted the values of the PostgreSQL configuration by fine-tuning the postgresql.conf server settings to achieve better performance. By default, Azure For PostgreSQL automatically adjusts these parameters based on the server resources. However, I fine-tuned them to optimize the database configuration further.</p><h3>Personal Thoughts and Feelings</h3><p>At the beginning, I have to admit, I saw the migration as an impossible task. Even with the help of the team&#39;s senior developer and software architect, we struggled to back up the database in the past. When the client made the request, I knew it would fall on my shoulders to handle it, and I didn’t have anyone else to turn to for help since I was the only one left from the original team.</p><p>To be honest, even the other teams and my technical leaders were scared of the request. And I felt the same way too. But then I remembered some advice from a really good content creator named midudev. He said that if no one else wants to touch a project, not even with a stick, it might be an opportunity to challenge yourself, learn a lot, and become a better software engineer.</p><p>So, with that mindset, I decided to embrace the challenge in a positive way. I knew I wasn’t a PostgreSQL expert at all, but I had some experience migrating smaller databases of 5 GB or 20 GB. However, handling a massive 3 TB transactional database was a whole different story.</p><p>Despite my initial fear, I took the leap and led the migration. I have to say, this challenge brought out the best in me. I’m happy to say I successfully completed the migration and even found ways to optimize certain aspects of the database.</p><p>Throughout the process, I learned so much. The migration really helped me understand the fundamentals of databases and how they work behind the scenes. It was an incredibly nourishing experience for me as a professional.</p><p>Looking back, if I faced the same situation again, I would approach it just like before. The sense of accomplishment and the knowledge gained were truly worth it.</p><p>Now that I know more about PostgreSQL, I would definitely consider using other migration tools like Barman or pgcopydb for incremental backups and more advanced migration tasks. Manual migration can be prone to mistakes, and these tools can provide more automation and reliability.</p><p>I’ve decided to write this article to share my entire migration experience. I believe it could be helpful to someone else who finds themselves in a similar situation. Sharing my journey and the lessons I’ve learned might offer valuable insights and encouragement to others facing challenging migrations.</p><h3>Conclusion</h3><p>In conclusion, migrating a colossal 3TB database was a challenging and complex task. It required in-depth knowledge of database fundamentals and involved a process of trial and error. Despite the difficulties, I learned valuable lessons and gained a deeper understanding of PostgreSQL.</p><p>Monitoring the migration progress was crucial for maintaining data integrity and performance. The experience pushed me to excel and optimize the database successfully.</p><p>I am eager to explore other migration tools for future projects. Writing this article has been a reflective journey, and I hope it can inspire and assist others facing similar challenges. Overall, the migration experience has strengthened my skills as a software engineer and reinforced my dedication to embracing technical challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1cf85c37bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-i-migrated-a-3tb-postgresql-transactional-database-ee1cf85c37bf">How I Migrated a 3 TB PostgreSQL Transactional Database</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>