Archivio annuale 28 December 2023

Un problema di Performance (con soluzione!)

C’è un detto che gira tra coloro che lavorano con il codice e che programmano: “Per quanto riguarda l’ottimizzazione di codice, non fare mai ottimizzazione di codice!” di questo stesso detto ne esiste una versione seguente che recita “Per quanto riguarda l’ottimizzazione di codice, non fare ottimizzazione di codice ORA”. L’idea alla base di questi detti è quella di non sprecare tempo e fatica nel fare ottimizzazione di codice quando, molto probabilmente, non hai ancora individuato se ne hai bisogno e se quello che stai ottimizzando è davvero cruciale. 

Per quanto riguarda l’ottimizzazione di codice, non fare mai ottimizzazione di codice

Un tipico esempio è minificare i file javascript e css, zippare il codice html di una pagina per ridurne la dimensione, ma poi arriva qualcuno e ci mette un immagine da 80 Mega non ottimizzata. Quindi anche se hai risparmiato 5Kb di file, l’immagina da 80Mega fondamentalmente distrugge tutto.

Alla radio dove ho una trasmissione (e sono anche responsabile tecnico) hanno un sito www.radiocittaperta.it e non mi sono mai trovato nella situazione di dover ottimizzare qualcosa: l’hosting dedicato e le soluzioni di cache del CMS non hanno mai mostrato colli di bottiglia del caso. 

Tuttavia c’è una funzionalità che ha dato del filo da torcere: il sito aggiorna in tempo reale il titolo della canzone in onda, l’immagine associata  e il programma in onda. Queste informazioni sono sparse su più fonti diverse: il titolo viene dal fornitore di streaming, il programma in onda è conservato sul database, l’immagine viene salvata sull’hosting del sito prendendola dalle API di Spotify. Per far si che le informazioni siano aggiornate costantemente quello che fa il sito (ma anche l’app) è chiamare un endpoint ogni 3 secondi. Immagino esistano anche modi più moderni e ottimizzati per fare questa cosa, ma il caro vecchio polling funziona da sempre. 

Il problema di chiamare un API ogni 3 secondi non è tanto nella chiamata, ma nel fatto che tale chiamata porta con se tutto il contesto, compreso il database e, per ogni chiamata, viene fatta una query per sapere che programma stia andando in onda. Non è micidiale, ma se siamo in parecchi sul sito e tutti sono fermi ad ascoltare e vedere la pagina, questo significa che per ogni utente, ogni 3 secondi, viene tirata su una connessione e viene fatta una query. E sta cosa non va benissimo, rallenta il sito e (a volte) lo rende inaccessibile con un errore del tipo “MOD_FCGID: CAN’T APPLY PROCESS SLOT PHP

Come si risolve questo problema ?

Ovviamente esistono numerose soluzioni: si potrebbe pensare di usare un database veloce, per esempio un noSql, oppure creare una tabella ottimizzata sul database MySql, ma ho preferito usare le conoscenze che ho acquisito durante una conferenza in Germania. Lì infatti, ho ascoltato un talk in cui si diceva che, nonostante una sfiducia generalizzata, spesso l’utilizzo di file di testo è la soluzione migliore e anche la più veloce. Questo perché hard disk e modi di accesso alle informazioni mantenute come file, possono essere anche molto, molto veloci.

Per questo ho impostato la creazione di un file di cache locale, con le informazioni salvate come testo:


{
title: "KATZENJAMMER con MIRO BARSA",
thumb: "https://www.radiocittaperta.it/wp-content/uploads/2020/09/KATZENJAMMER-IMAGE.png",
show_podcastfilter: "katzenjammer",
url: "https://www.radiocittaperta.it/shows/katzenjammer-con-miro-barsa/",
day: 4,
start: "10:00",
end: "12:00",
category: "0",
song: "Pink Floyd - Whish you were here",
cover: "https://www.radiocittaperta.it/wp-content/uploads/2020/09/wish-you-were-here.png"
}

Come gestisci l’aggiornamento titolo o programma in onda?

Per il titolo la cosa è piuttosto semplice: quando lo speaker aggiorna il titolo, allora viene aggiornato anche il file di cache sul sito. Questo perché il titolo della canzone in onda non arriva da un posto magico, ma è inserito a mano dallo speaker di turno, ad ogni cambio canzone. 

Per il programma in onda invece ho usato cron di wordpress, che ogni 15 minuti fa la query e aggiorna il file con i dati reali. 15 minuti è un tempo ragionevole e poi, di base, l’idea è che le trasmissioni cambino all’ora o’clock, o (al massimo) al 30esimo minuto. Quindi ogni 15 minuti è più che sufficiente.

Come leggi le informazioni?

Questo è facilissimo, con una chiamata ajax direttamente dal sito (o con una chiamata dall’app) viene richiesto il file statico, per esempio in questo modo:


var proxyURL = "https://www.radiocittaperta.it/mystaticfile.json";
jQuery.ajax({
     type: "GET",
     cache: false,
     url: proxyURL,
     async: true,
     dataType: "json",
  success: function(data) {
      applyTitle(data)
  },
  error: function(e) {}
})

Non entro nel merito della funzione applyTitle di base si preoccupa di aggiornare titolo, immagine e trasmissione in onda.

A performance problem (and a solution!)

There is a saying among those who work with code”When it comes to code optimization, never do code optimization!” of this same saying there is a following version that states “As far as code optimization is concerned, don’t do code optimization NOW”. The idea behind these sayings is to not waste time and effort doing code optimization when, most likely, you have not yet identified whether you need it and whether what you are optimizing is crucial.

When it comes to code optimization, never do code optimization

A typical example is minifying javascript and css files, zipping the html code of a page to reduce its size, but then someone comes and publishes an 80 Mega non-optimized image. So even if you saved 5Kb of files, the 80Mega image destroys everything.

As regards the radio website, www.radiocittaperta.it, I have never found myself in the situation of having to optimize something: the dedicated hosting, the caching solutions implemented within the CMS in use, the manageable traffic, have never shown bottlenecks of the case.

However, there is one feature that has given us a hard time: the site updates in real-time the title of the song on air, the image associated with that song, and the program on air. This information is spread across different sources: the title comes from the streaming provider, the broadcast program is stored on the site’s database, and the image is saved on the site’s hosting by taking it from Spotify’s API. To ensure that the information is constantly updated, the site (but also the app) does is call an endpoint to receive updated information every 3 seconds. I guess there are more modern and optimized ways to do this too, but good old polling has worked for years and I know it quite well.

The problem of calling an API every 3 seconds from the browser is not so much in the call, but this call brings with it the whole context including the database and, for each call, a query is made to know which program is on air. It’s not deadly, but if there are several of us on the site, and everyone is still listening and seeing the page, this means that for each user, every 3 seconds, a connection is pulled up and a query is made. And this isn’t very good, it slows down the site and (sometimes) makes it inaccessible with an error like “MOD_FCGID: CAN’T APPLY PROCESS SLOT PHP

How is this problem solved?

There are numerous solutions: you could think of using a fast database, for example, a NoSQL, or creating an optimized table on the MySql database, but I preferred to use the knowledge I acquired during a conference in Germany. There I listened to a talk in which it was said that, despite a general mistrust, the use of text files is often the best solution and also the fastest. This is because hard drives and ways of accessing information kept as files can also be very, very fast. For this I set up the creation of a local cache file, with the information saved as text, the information is formatted like this:


{
title: "KATZENJAMMER con MIRO BARSA",
thumb: "https://www.radiocittaperta.it/wp-content/uploads/2020/09/KATZENJAMMER-IMAGE.png",
show_podcastfilter: "katzenjammer",
url: "https://www.radiocittaperta.it/shows/katzenjammer-con-miro-barsa/",
day: 4,
start: "10:00",
end: "12:00",
category: "0",
song: "Pink Floyd - Whish you were here",
cover: "https://www.radiocittaperta.it/wp-content/uploads/2020/09/wish-you-were-here.png"
}

 

How do you handle updating the title or program on air?

For the title the thing is quite simple: when the speaker updates the title, then the cache file on the site is also updated. This is because the title of the song on air does not come from a magical place, but is inserted manually by the speaker on duty, at each song change. For the program on air, however, I used WordPress cron, which runs the query every 15 minutes and updates the file with the real data. 15 minutes is a reasonable time and then, basically, the idea is that broadcasts change at the hour o’clock, or (at most) on the 30th minute. So every 15 minutes is more than enough.

How do you read the information?

This is very easy, with an ajax call directly from the site (or with a call from the app) the static file is requested, for example like this:


var proxyURL = "https://www.radiocittaperta.it/mystaticfile.json";
jQuery.ajax({
     type: "GET",
     cache: false,
     url: proxyURL,
     async: true,
     dataType: "json",
  success: function(data) {
      applyTitle(data)
  },
  error: function(e) {}
})

I won’t go into the merits of the basic applyTitle function, which takes care of updating the title, image, and broadcast.

Natale 2023

L’aperitivo da Gino (Club della Roma) un cenone diverso ma buonissimo, molti malati ma nessuno grave, una macchina che doveva essere pronta a ferragosto ma che non è neanche stata portata da Babbo Natale, un poco di raffreddore, partita a Trivial Pursuit e le solite lamentele per l’edizione vecchia del gioco. 

 

Non è per Sempre

Mercoledì 20 Dicembre è andato in scena uno spettacolo preparato in mille condizioni avverse. Uno spettacolo molto ricco di emozioni fortemente contrastanti. “Si ride, si riflette, ci si emoziona” Queste le parole delle regista Laura Jacobbi a descrizione del bellissimo spettacolo.

Foto di Giovanna Onofri

 

Katzenjammer dell’18 Dicembre 2023

Playlist del 18 Dicembre 2023 di Katzenjammer

 

Pharrell Williams, Swae Lee, Rauw Alejandro – Airplane Tickets
Green Day – Dilemma
IDLES – Grace
Bologna Violenta – Tuk
Andrea Satta, Giovanni Truppi – Abbi pazienza
Killing Joke – Eighties
Bambole Di Pezza – Riparliamone Domani
Daniele Silvestri, Fulminacci – L’uomo nello specchio
CAKE – The Distance
Achille Lauro – Stupidi Ragazzi
Fontaines D.C. – Boys In the Better Land
Kate Bush – Wuthering Heights
Krisma – Black Silk Stocking
Fleetwood Mac – The Chain
Pearl Jam – Alive
Pulp – This Is Hardcore

Katzenjammer dell’11 Dicembre 2023

Scaletta di Katzenjammer dell’11 Dicembre 2023



Eliza Rose, Calvin Harris – Body Moving
Margherita Vicario – Magia
Guns N’ Roses – The General
Placebo – Running Up That Hill
Muse – Apocalypse Please
Lana Del Rey – Take Me Home, Country Roads
Max Gazzè – L’epica della guerra
I CANI BAUSTELLE – Nabucconodosor – Essere vivo
Frank Carter & The Rattlesnakes – Brambles
M¥SS KETA – CONDANNATA A DANZARE
Garbage – Only Happy When It Rains
Porno for Pyros – Agua
Tropea – Discoteca
Wolf Alice – Don’t Delete The Kisses
The Fratellis – Chelsea Dagger
Kaiser Chiefs – Everyday I Love You Less And Less
The Kooks – Naive

Katznejammer del 4 dicembre 2023

Scaletta di Katznejammer del 4 dicembre 2023



Beyonce – MY HOUSE
Subsonica – Adagio
The Beach Boys – Barbara Ann
The Jesus and Mary Chain – jamcod
Björk, ROSALÍA – Oral
R.E.M. – Oh My Heart
Gossip – Crazy Again
H.E.R., Foo Fighters – The Glass
The Cure – Lullaby
Spirytus96 – Vino
The 1975 – Give Yourself A Try
Mumford & Sons – Little Lion Man
Arctic Monkeys – Fireside
The Strokes – You Only Live Once
The Smiths – There Is a Light That Never Goes Out
Air, Beth Hirsch – You Make It Easy

Katzenjammer del 27 novembre 2023

Playlist del 27 novembre 2023

Jack Harlow – Lovin On Me
Fulminacci, Pinguini Tattici Nucleari – Puoi
Morgan, Pasquale Panella – Sì, certo l’amore
The Rolling Stones, Purple Disco Machine – Mess It Up
Escape The Curfew – Devil’s Advocate
Green Day – Look Ma, No Brains!
CCCP – Fedeli Alla Linea – Live In Pankow
Eugenio In Via Di Gioia – Stormi
Iosonouncane – Stormi
Depeche Mode – Precious
La Crus, Carmen Consoli – Io Confesso
Yeah Yeah Yeahs – Heads Will Roll
Elisa – Quando Nevica
Mumford & Sons – Winter Winds
Portishead – Sour Times
Massive Attack, Tracey Thorn – Protection