Say goodbye to fighting with -Xmx on ZGC

Reviewing and setting up JVM configurations, there’s one thing I’ve seen over and over: sizing the heap properly is not easy. Many companies get it wrong and, on top of that, apply the same configuration to all their services, whatever load each one has. The result ends up hurting both the application itself and the system it runs on: set it too low and the GC eats your CPU; set it too high and you starve every other process of memory.

That’s why I find JEP 546 (Adaptive Heap Sizing for ZGC) so interesting. It’s planned for JDK 28, in March 2027. All you’ll need is to start your application like this:

java -XX:+UseZGC -XX:+ZAdaptiveHeapSizing …

and you’ll no longer have to set -Xmx or -XX:SoftMaxHeapSize by hand. With this option enabled, ZGC:

– Uses a default maximum heap size of 100% of physical memory, minus a small reserve.
– Adaptively adjusts the heap size to balance memory usage against the CPU consumed by the GC.
– Behaves like a “good neighbor”: it expands or contracts the heap as memory and CPU usage change across the host system.

If you still want to fine-tune, there’s just one setting left to adjust, -XX:ZGCIntensity (default 5), to choose between spending less CPU or less memory.

The catch? It’s optional, it only applies to ZGC, and since the default maximum goes from 25% to 100% of physical memory, your application may use more memory than before. It will need proper testing before going to production.

https://lnkd.in/e_nEHpWV

Run Your Own Free and Private AI Assistant with Continue + Ollama

Would you like to have a local chat model running for free and in a private environment? Here are the steps I followed:

– Install the Continue extension in IntelliJ or Visual Studio Code.
– Install Ollama locally.
– Pull an open-source LLM such as Llama 3, Mistral, or Gemma (I installed Llama in my case).
– Optionally, install an autocomplete model so that Continue can provide in-editor code suggestions, similar to Copilot.
– Use the agent just like you would use ChatGPT, but free and private.


What are these components?
– Continue → the IDE extension that gives you the chat panel and autocomplete features. It’s the interface you see in VS Code or IntelliJ.
– Ollama → the local engine that runs large language models on your machine. It exposes an API at http://localhost:11434, which Continue connects to.
– The LLM (e.g., Llama 3, Mistral, Gemma) → the actual model that generates responses. Ollama downloads and manages these models for you.
– Autocomplete model → a smaller, faster model optimized to suggest code as you type, similar to Copilot.

👉 If you want to connect your agent with MCP servers, ensure the version of Continue (and the model you use) includes tool calling as a built-in feature. I used Llama 3.1.

I’m currently working on connecting my agent to my own MCP endpoint. Once I have it running, I’ll share the details here.

For software engineering tasks, a strong open-source option is Devstral.

On the SWE-Bench benchmark, it achieves 46.8%, outperforming models such as Claude 3.5 Haiku (40.6%) and GPT-4.1-mini (23.6%).


https://www.modelscope.cn/models/mistralai/Devstral-Small-2505

To use it, once installed ollama run:
ollama run unsloth/devstral-small-2505-gguf:Q4_K_M


Have a great day!

Nuria

New Security Options in Spring Boot: Passkeys

I learned about passkeys during the security workshop at Spring IO 2025.

Passkeys offer a simpler and safer alternative to traditional passwords. Instead of remembering complex passwords, passkeys use secure cryptographic keys stored directly on your device.

This method adheres to standards established by the FIDO (Fast Identity Online) Alliance and utilizes the WebAuthn (Web Authentication) protocol. With passkeys, you log in effortlessly using biometrics, a device PIN, or security keys.

FIDO ensures your credentials remain private and secure, while WebAuthn makes it easy for browsers and apps to support passkey logins. This reduces common risks, such as phishing and password theft, making passkeys a user-friendly and secure authentication option.

While not yet supported by all operating systems, passkeys can still be utilized through external apps, such as 1Password, on platforms without native support.

Steps to Implement Passkeys in Your Spring Boot Project

To use Passkeys, even locally, we must enable HTTPS in our project. We’ll create a trusted certificate tied to a local domain.

1 – Install mkcert tool

To generate a trusted local certificate easily, download and install the mkcert tool.

2 – Add a new local domain

RFC 2606 officially reserves the following domains for local testing and development purposes:

  • .test
  • .example
  • .invalid
  • .localhost

We will choose .test. Edit your local etc/hosts file (or system equivalent) and add:

127.0.0.1 myapp.test

3 – Generate the certificate

First install locally the certificate: mkcert -install.

Then create your certificate with the following command:

mkcert -pkcs12 -p12-file myapp-server-keystore.p12 127.0.0.1 localhost myapp.test

You will see a confirmation message indicating the PKCS#12 bundle (myapp-server-keystore.p12) was created and the password by default that is changeit (we will use in application properties).

4 – Save the certificate in your project

Place the generated myapp-server-keystore.p12 file into your project’s /src/main/resources folder.

Configure the Spring Boot project to use the new certificate

In the application properties, add the following configuration:

spring:
  application:
    name: passkeys
  ssl:
    bundle:
      jks:
        localhost:
          key:
            password: changeit
          keystore:
            location: classpath:myapp-server-keystore.p12
            password: changeit
            type: PKCS12
server:
  port: 8443
  ssl:
    enabled: true
    bundle: localhost
  http2:
    enabled: true
  address: myapp.test

Extend the WebSecurityConfiguration to enable Passkeys

headers.httpStrictTransportSecurity(HstsConfig::disable))
            .httpBasic(withDefaults())
            .formLogin(withDefaults())
            // Specific configutation for Passkeys and WebAuthn:
            .webAuthn(webAuthn -> webAuthn
                .rpName("Spring Security PassKeys")     
                .rpId("myapp.test")                         /
                .allowedOrigins("https://myapp.test:8443")  
            );

For the test we will add a user in memory:

@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
User
.builder()
.username("user")
.password("password")
.passwordEncoder(passwordEncoder()::encode)
.roles("USER")
.build()
);
}

Testing the Application

Below is a video showing the new app in action.

Initially, the user logs into the application using their username and password. After this first login, the user can register a passkey to switch to a passwordless login method for future access.

Once registered, the user can access the system using their Passkey.

GitHub project demo: https://github.com/nuriaruiz/passkey

Nuria

RAG en Spring Boot: indexa tu BD relacional en PGVector y consulta con OpenAI


Si quieres crear tu propia base de datos vectorial en Postgres (PGVector) y poblarla automáticamente con datos de tu base relacional para usarla como contexto en OpenAI, sigue estos pasos:


Dependencias Maven

<dependencies>
  <!-- Embeddings y Chat con OpenAI -->
  <dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
  </dependency>

  <!-- Vector store sobre Postgres (PGVector) -->
  <dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
  </dependency>

  <!-- Acceso a BD relacional -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>
  <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>


Preparar la base de datos

  1. Activa la extensión vectorial: CREATE EXTENSION IF NOT EXISTS vector;
  2. Para mi POC voy a usar una tabla puertas que tiene al menos campos:
    • id (PK)
    • modelo, madera (VARCHAR)
    • entrada, blindada, relieve, cristal1…cristal12 (BOOLEAN)
    • total (NUMERIC) → precio en euros

Configuración en application.yml

spring:
  datasource:
    url: jdbc:postgresql://…  
    username: …  
    password: …  
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
    embeddings-model: text-embedding-ada-002
    vectorstore:
      index: pgvector
      pgvector:
        datasource: default
        initialize-schema: true
        index-type: HNSW
        distance-type: COSINE_DISTANCE
        dimensions: 1536


Carga de datos (“ingestión”)

En el ejemplo que estamos viendo, vamos a alimentar el Vector Store con la infomación almacenada en una base de datos relacional, pero bien podría ser obtener la información de un endpoint específico de GitHub, de BitBucket, de un fichero.. cualquier fuente de entrada.

Es importante tener una buena descripción del contenido, ya que basado en éste creará un embedding y se buscará similitudes con la búsqueda.
En mi caso, y en esta primera versión, hago una pequeña ayuda indicando a partir de que rango considero un precio barato, caro o precio medio. Teniendo en cuenta que muchas búsquedas se harán sobre este texto.

Tener en cuenta que el metadata no influye en la inferencia, lo tenemos como soporte al post procesamiento del dato; filtrado, ordenación o formateo.

En un ApplicationRunner (ejecutar solo una vez con un flag de control):

@Bean
ApplicationRunner loader(
    TokenTextSplitter splitter,
    JdbcClient db,
    VectorStore vs
) {
  return args -> {
    List<Puerta> puertas = db
      .sql("SELECT * FROM puertas")
      .query(new DataClassRowMapper<>(Puerta.class))
      .list();

    puertas.forEach(p -> {
      double precio = p.getTotal().doubleValue();

      // Categoría semántica de precio
      String catPrecio = precio <= 500 ? "barata"
                          : precio <= 800 ? "precio medio"
                                          : "cara";

      // Genera descripción dinámica
      String desc = String.format(
        "Puerta %s, madera %s, %s, %s, %s, cristales: %s. Precio: %.2f €. Categoría: %s.",
        p.getModelo(),
        p.getMadera(),
        p.getEntrada()  ? "entrada" : "interior",
        p.getBlindada() ? "blindada" : "sin blindaje",
        p.getRelieve()  ? "con relieve" : "sin relieve",
        obtenerCristales(p),
        precio,
        catPrecio
      );

      // Metadatos
      Map<String,Object> meta = Map.of(
        "modelo",          p.getModelo(),
        "madera",          p.getMadera(),
        "precio",          precio,
        "categoria_precio",catPrecio
      );

      Document doc = new Document(desc, meta);
      vs.add(splitter.apply(List.of(doc)));
    });
  };
}

Tip: TokenTextSplitter lo defines así:

@Bean TokenTextSplitter tokenTextSplitter() {
  return new TokenTextSplitter();
}

Con esto obtenemos el VectorStore:


Endpoint REST para consultas

En este ejemplo final de promt estamos haciendo un post procesamiento cualquiera, como ordenar por puertas baratas.

Es un ejemplo y dado el metadata podremos hacer tanto post procesamiento como necesitemos para nutrir y mejorar la respuesta final al usuario.

En este caso, ya que la POC trata de una respuesta a una búsqueda del usuario en una página de puertas (actualmente in progress :)), devolvería la respuesta de OpenAI más un enlace hacia la sección de la puerta o puertas seleccionadas.

En el ejemplo, también he puesto un template para el agente muy sencillo, “Eres un experto en puertas. Usa solo la información del contexto”, habría que darle bastante más contexto para que su comportamiento fuese más acertado.

@RestController
@RequestMapping("/api/puertas")
public class PuertasController {

  private final VectorStore vs;
  private final ChatModel chatModel;

  public PuertasController(VectorStore vs, ChatModel chatModel) {
    this.vs = vs;
    this.chatModel = chatModel;
  }

  @GetMapping("/query")
  public String query(@RequestParam String q) {
    // 1) Semántica: trae N candidatos
    List<Document> docs = vs.similaritySearch(q);

    // 2) Filtra categoría “barata” (o usa todos si no hay)
    List<Document> baratos = docs.stream()
      .filter(d -> "barata".equals(d.getMetadata().get("categoria_precio")))
      .toList();
    if (baratos.isEmpty()) baratos = docs;

    // 3) Elige el de menor precio
    Document mejor = baratos.stream()
      .min(Comparator.comparing(d ->
        ((Number)d.getMetadata().get("precio")).doubleValue()
      ))
      .orElse(baratos.get(0));

    // 4) Prompt para OpenAI
    String prompt = """
      Eres un experto en puertas. Usa solo la información del contexto.
      Pregunta: %s

      Contexto:
      %s
      """.formatted(q, mejor.getText());

    // 5) Llamada y respuesta
    return chatModel.call(prompt);
  }
}


Resultado

Tenemos un flujo RAG completo:

  1. Índice vectorial en Postgres
  2. Ingestión desde una BD relacional
  3. Búsqueda semántica + lógica de precio
  4. Llamadas a OpenAI con contexto preciso

Prueba

Ante la petición sencilla de: “Estoy buscando una puerta de roble barata”, el agente devolvería la siguiente información: “La puerta que buscas es el modelo ODIN, fabricada en madera de roble. Es una puerta de interior, sin blindaje ni relieve, y no tiene cristales. Su precio es de 464.72 euros, lo que la considera una opción barata.”

Que acompañaríamos con un enlace a la puerta para obtner más información y poder verla.

Espero que os haya resultado interesante.

Nuria